为了账号安全,请及时绑定邮箱和手机立即绑定

在迭代“for-loop”时设置字典值

在迭代“for-loop”时设置字典值

catspeake 2021-12-26 14:19:24
我正在尝试创建一个嵌套字典,其中包含一组从 for 循环中提取的值,以衡量各种客户-产品配对的增长和收入金额。但是,当我遍历数据框以设置字典元素时,每个字典元素最终都具有相同的值。这里发生了什么?我已经尝试更改列表构建方式的各种元素,但无济于事。'''TP_Name = customer nameService_Level_1 = service name100.2014 is just a marker to show that someone has started consuming the servicetpdict is already created with necessary nesting below with empty values at each endpoint'''for col in pivotdf.columns:  growthlist = []  amountlist = []  first = True  TP_Name, Service_Level_1 = col.split('___')  for row in pivotdf[col]:    if first == True:      past = row+.00001      first = False    if row == 0 and past <.0001 :      growth = 0    elif row != 0 and past == .00001:      growth = 100.2014    else:      current = row      growth = (current-past)/past    growth = round(growth,4)    growthlist.append(growth)    past = row +.00001    amountlist.append(row)  tpdict[TP_Name][Service_Level_1]['growth'] = growthlist  tpdict[TP_Name][Service_Level_1]['amount'] = amountlist'''problem: Each value ends up being the same thing'''Expected results:{'CUSTOMER NAME': {'PRODUCT1': {'growth': [unique_growthlist],   'amount': [unique_amountlist]},  'PRODUCT2': {'growth': [unique_growthlist],'amount': [unique_amountlist]}}}
查看完整描述

1 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

字典是一个键值对(我相信你可能知道)。如果您尝试使用字典中已存在的键写入字典,则字典将覆盖该键的值。


例子:


d = dict()

d[1] = 'a' # d = {1: 'a'}

d[1] = 'b' # d = {1: 'b'}

您的项目似乎可以很好地使用namedtuplepython 中的 a 。Anamedtuple基本上是一个轻量级的类/对象。我的示例代码可能是错误的,因为我不知道你的for循环是如何工作的(评论对每个人都有帮助)。这就是一个例子。


我只提出这个建议,因为比dictionaries它们持有的对象多消耗大约 33% 的内存(尽管它们要快得多)。


from collections import namedtuple


Customer = namedtuple('Customer', 'name products')

Product = namedtuple('Product', 'growth amount')


customers = []

for col in pivotdf.columns:

    products = []

    growthlist = []

    amountlist = []

    first = True

    TP_Name, Service_Level_1 = col.split('___')

    for row in pivotdf[col]:

        if first == True:

            past = row + .00001

            first = False

        if row == 0 and past < .0001 :

            growth = 0

        elif row != 0 and past == .00001:

            growth = 100.2014

        else:

            current = row

            growth = (current - past) / past

        growth = round(growth, 4)

        growthlist.append(growth)

        past = row + .00001

        amountlist.append(row)


    cur_product = Product(growth=growthlist, amount=amountlist) # Create a new product

    products.append(cur_product) # Add that product to our customer


# Create a new customer with our products

cur_customer = Customer(name=TP_Name, products=products)

customers.append(cur_customer) # Add our customer to our list of customers


这customers是namedtuples我们可以用作对象的 Customer 列表。例如,这就是我们如何将它们打印出来。


for customer in customers:

    print(customer.name, customer.products) # Print each name and their products

    for growth, amount in customer.products:

        print(growth, amount) # Print growth and amount for each product.


查看完整回答
反对 回复 2021-12-26
  • 1 回答
  • 0 关注
  • 232 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号