我是Python的新手。如果我有一個這樣的「數據」變量:Python中兩個列表的交匯點
data = [['water', 'chips', 'pie', 'fruit', 200], ['soda', 'nuts', 'cake', 'vegetables', 300], ['water', 'chips', 'cake', 'fruit', 40], ['soda', 'crackers', 'cake', 'vegetables', 80]]
,我有一個這樣的名單:
ls = [['water', 'chips'], ['soda', 'nuts']]
我怎樣才能返回data[i][4] for i in data
包含這兩個值,並追加其總和到名單。
total = 0
for i in data:
for x in ls
if i contains x:
ls[2] = total += total
# should return
ls = [['water', 'chips', 240], ['soda', 'nuts', 300]]
的最後一個元素中ls
是那些data[3][4]
的總和包含ls[1]
和ls[2]
我將刪除我的答案,我建議你閱讀教程,因爲你的索引不會接近你的邏輯,'data [3] [4]'是80.另外x不能包含我,因爲x是一個列表。你將不得不看看x和i中的每一個元素,並且比較一下,如果有趣的東西可以出現在任何地方 –