简体   繁体   中英

How to use .count to calculate number of times each item in one list appears in another list in python?

I am attempting to calculate the number of times each item in one list appears in another list using python's .count. This is what I have:

tentslist = ['E4', 'C2', 'C8', 'G8', 'G1', 'A7', 'C5', 'G4', 'A5', 'E1', 'E6', 'A3']
x1t = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8']

print(x1t.count(tentslist[0-11]))

The output I am looking for is 3, however I am getting 0. Why is this? How do I fix this?

Thankyou.

Problem is it's looking to count the amount of times the entire tentslist is in x1t. Which is indeed 0.

What you seem to want is how many times an element from x1t is in tentslist? Then this will be a solution

tentslist = ['E4', 'C2', 'C8', 'G8', 'G1', 'A7', 'C5', 'G4', 'A5', 'E1', 'E6', 'A3']
x1t = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8']

count = 0
for x in x1t:
    count += tentslist.count(x)

print(count)

This can be achive by using the list comprehension

count = sum([x1t.count(x) for x in tentslist])

This is at first counting the occurences for each element and later on sums them to get the total result

Edit: As suggested in the comments one can also remove the list comprehension entirely and just uses this

count = sum(x1t.count(x) for x in tentslist)

you need intersection?

len( set(x1t) & set(tentslist) )

Output:3

Following is the syntax for count() method: list.count(obj) obj is the object to be counted in the list.

Your code will return not null only there:

tentslist = ['E4', 'C2', 'C8', 'G8', 'G1', 'A7', 'C5', 'G4', 'A5', 'E1', 'E6', 'A3']
x1t = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', ['E4', 'C2', 'C8', 'G8', 'G1', 'A7', 'C5', 'G4', 'A5', 'E1', 'E6', 'A3']]

print(x1t.count(tentslist))

output: 1

Use:

tentslist = ['E4', 'C2', 'C8', 'G8', 'G1', 'A7', 'C5', 'G4', 'A5', 'E1', 'E6', 'A3']
x1t = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8']
matches = set(x1t) & set(tentslist)
match_count = len(matches)

sum(x1t中x的tentslist.count(x))

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