编辑 - 使用字典:
现在你已经指定您希望如何处理你的数据,我倒是强烈推荐切换到使用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']]]
'fruits'不显示有效的Python结构。 –
(继续从@ IgnacioVazquez-Abrams所说的话):无论如何,都不像书面那样。你错过了几个逗号。 –
你正在覆盖'价格'。 –