2015-07-12 59 views
1

我是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]

+0

我將刪除我的答案,我建議你閱讀教程,因爲你的索引不會接近你的邏輯,'data [3] [4]'是80.另外x不能包含我,因爲x是一個列表。你將不得不看看x和i中的每一個元素,並且比較一下,如果有趣的東西可以出現在任何地方 –

回答

1
res = [ 
    e + # filter list itself 
    [ 
     sum(# sum all 
      l[4] # get fourth item if contains all 
      for l in data # take each element of data 
      if all(i in l for i in e) # check if contains all filter list 
     ) 
    ] # concat sum to list itself 
    for e in ls # take each element of filter list 
] 
+0

有沒有一種簡單的方法,我可以找到「all(i in l for i in e)」的次數真的,以便我可以將它除以總和以產生平均值? – Himmel

+0

@Himmel如果你使用py3,只需用[statistics.mean]替換sum(https://docs.python.org/3/library/statistics.html?highlight=average#statistics.mean)。如果列表中沒有項目,則可以將'[0]'連接到結果列表,即'statistics.mean([0] + [...])''。否則,編寫你的函數來取得一個列表的平均值,並用你的'sum'替換'sum',這樣'def avg(ls):return sum(ls)/ len(ls)'。 –

0

這裏是我的方法:使用從收藏的反跟蹤的總和。我們使用的每個子列表中的前兩個項目作爲重點,而最後一個項目的價值:

from collections import Counter 

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

counter = Counter() 
for item in data: 
    if item[:2] in ls: 
     counter.update({tuple(item[:2]): item[-1]}) 

result = [list(k) + [v] for k, v in counter.iteritems()] 
print result 

由於Counter行爲就像一本字典和詞典不採取列表作爲關鍵,我們必須將前兩個元素的列表放入一個元組(因此爲tuple(item[:2]))。