2016-04-25 50 views
1

我想計算總項目的列表中包含「A」的特定項目,這應該是4 + 3 = 7怎麼算的總項數的列表包含在Python

tweetword = (['a','b','c','a'],['a','e','f'],['d','g']) 
count_total_a = {} 
for t in tweetword: 
    for word in tweetword: 
     if word not in count_total_a: 
      count_toal_a[word] = len(t) 
     if word in count_total_a: 
      count_total_a[word] += len(t) 
'''the result I get is not correct coz it counts the first list twice''' 

真的很感謝任何幫助!

回答

3

以總和超過發電機:

sum(len(x) for x in tweetword if 'a' in x) 
-1
tweetword = (['a','b','c','a'],['a','e','f'],['d','g']) 

contains_a = [tweet for tweet in tweetword if 'a' in tweet] 

sum_lengths = sum(map(len, contains_a)) 

print(sum_lengths) 
相關問題