如何为每个列表项生成列表

2024-09-28 01:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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']

非常感谢你的帮助,我还在学习


Tags: in名称apple列表fornames价格banana
2条回答

编辑-使用词典:

既然您已经指定了如何操作数据,我强烈建议您改用dictionary而不是列表。由于键和值的关联是如何工作的,字典将允许您通过比数字索引更具描述性的值来访问特定项,就像列表那样。您的新代码如下所示:

>>> names = ['apple', 'banana', 'orange']
>>> prices1 = ['0.40', '1.20', '0.35']
>>> prices2 = ['0.43', '1.21', '0.34']
>>> 
>>> fruits = {}     # fruits is now a dictionary, which is indicated by the curly braces
>>> for i in range(len(names)):
...     fruits[ names[i] ] = [ prices1[i], prices2[i] ]
... 
>>> print(fruits)
{'orange': ['0.35', '0.34'], 'apple': ['0.40', '0.43'], 'banana': ['1.20', '1.21']}

如果你需要查看某一特定水果的价格,你可以随时使用:

^{pr2}$

同样,要添加新价格,只需键入:

>>> fruits['banana'].append('1.80')
>>> print( fruits['banana'] )
['1.20', '1.21', '1.80']

除去价格:

>>> fruits['orange'].remove('0.34')
>>> print( fruits['orange'] )
['0.35']

要在字典中插入一个全新的项,只需使用=运算符将属性赋给新键:

>>> fruits['durian'] = ['2.25', '2.33']
>>> print( fruits )
{'orange': ['0.35'], 'durian': ['2.25', '2.33'], 'apple': ['0.40', '0.43'], 'banana': ['1.20', '1.21', '1.80']}

要删除一个项目,只需调用pop方法:

>>> fruits.pop('apple')
['0.40', '0.43']
>>> print( fruits )
{'orange': ['0.35'], 'durian': ['2.25', '2.33'], 'banana': ['1.20', '1.21', '1.80']}

这样一来,你就可以更清楚地知道在任何给定的时间里你在操纵什么,而不是试图在模糊的列表索引中混日子。在

但是,如果你必须使用列表,请参考下面我的旧答案。在


旧答案:

假设所使用的两个价格表应分配给两个不同的变量,一个解决方案是迭代列表,如下所示:

>>> names = ['apple', 'banana', 'orange']
>>> prices1 = ['0.40', '1.20', '0.35']
>>> prices2 = ['0.43', '1.21', '0.34']
>>>
>>> fruits = []
>>> for i in range(len(names)):
...     fruits.append( [ names[i], [prices1[i], prices2[i]] ] )
...
>>> fruits
[['apple', ['0.40', '0.43']], ['banana', ['1.20', '1.21']], ['orange', ['0.35', '0.34']]]

您可以使用^{}两次:

names = ['apple', 'banana', 'orange']
prices1 = ['0.40', '1.20', '0.35']
prices2 = ['0.43', '1.21', '0.34']
fruits = list(zip(names, zip(prices1, prices2)))

在python3中,zip是一个生成器,因此我们使用fruits = list(...)将生成器转换为列表。在

相关问题 更多 >

    热门问题