简体   繁体   中英

how to count the total number of items for the lists contain a specific item in python

I want to get count the total items for the lists contain 'a', which should be 4+3 = 7

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

Really appreciate any help!

将总和乘以一个生成器:

sum(len(x) for x in tweetword if 'a' in x)
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM