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

时间:2015-10-21 04:33:38

标签: python python-3.x

names = ['apple', 'banana', 'orange']
prices1 = ['0.40', '1.20', '0.35']
prices2 = ['0.43', '1.21', '0.34']

如何为每个名称生成一个列表并将价格附加到该列表中

例如

fruits = [['apple', ['0.40', '0.43']],
          ['banana', ['1.20', '1.21']], 
          ['orange', ['0.35', '0.34']]]

这就是我一直在尝试使用的:

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用zip两次:

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(...)将生成器转换为列表。

答案 1 :(得分:1)

编辑 - 使用词典:

现在您已经指定了操作数据的方式,我强烈建议切换到使用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']}

如果您需要检查特定水果的价格,您可以随时使用:

>>> print( fruits['apple'] )
['0.40', '0.43']

同样,为了添加新价格,您只需输入:

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