編輯 - 使用字典:
現在你已經指定您希望如何處理你的數據,我倒是強烈推薦切換到使用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所說的話):無論如何,都不像書面那樣。你錯過了幾個逗號。 –
你正在覆蓋'價格'。 –