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.
添加回答
举报
