names = ['apple', 'banana', 'orange']
prices1 = ['0.40', '1.20', '0.35']
prices2 = ['0.43', '1.21', '0.34']
如何为每个名称生成一个列表并在该列表中追加价格
例如
^{pr2}$这就是我一直想用的:
x = 0
n = len(names)
fruits = [[] for name in names]
for i in prices:
for x in range(0, n-1):
x += 1
fruits[x].append(prices[x])
编辑
我希望能够操纵-添加/删除价格-生成的列表,如
print[apple]
['0.40', '0.43']
或apple.append(prices3[x])
['0.40', '0.43', 'x']
非常感谢你的帮助,我还在学习
编辑-使用词典:
既然您已经指定了如何操作数据,我强烈建议您改用dictionary而不是列表。由于键和值的关联是如何工作的,字典将允许您通过比数字索引更具描述性的值来访问特定项,就像列表那样。您的新代码如下所示:
如果你需要查看某一特定水果的价格,你可以随时使用:
^{pr2}$同样,要添加新价格,只需键入:
除去价格:
要在字典中插入一个全新的项,只需使用
=
运算符将属性赋给新键:要删除一个项目,只需调用
pop
方法:这样一来,你就可以更清楚地知道在任何给定的时间里你在操纵什么,而不是试图在模糊的列表索引中混日子。在
但是,如果你必须使用列表,请参考下面我的旧答案。在
旧答案:
假设所使用的两个价格表应分配给两个不同的变量,一个解决方案是迭代列表,如下所示:
您可以使用^{} 两次:
在python3中,
zip
是一个生成器,因此我们使用fruits = list(...)
将生成器转换为列表。在相关问题 更多 >
编程相关推荐