简体   繁体   中英

How can I count the item in a list like this

There are 3 items, 'Peter', 'Tom, 'Vincent'

if I want to input 5 times to check how many times my inputs match the required items, what should I use?

I tried .count method but it did not match my requirement...

For example,

my inputs:

Tom

David

David

Vincent

Sam

Expected output should be: Number = 2

Should I use list or dict or other methods?

Just use a loop that increments a counter.

count = 0
items = ['Peter', 'Tom', 'Vincent']
inputs = ['Tom', 'David', 'David', 'Vincent', 'Sam']
for el in inputs:
    if el in items:
        count += 1
print("Number =", count)

Assuming you want a list intersection of your inputs with required items

seek = ['Peter', 'Tom', 'Vincent']
my_inputs = ['Tom', 'David', 'David', 'Vincent', 'Sam']

len([x for x in my_inputs if x in seek]) // 2

So basically for each of your input, you wanna see if it matches any item in seek. Simply build such a list of intersection, and do len on it

your inputs may repeat:

seek = ['Peter', 'Tom', 'Vincent']
my_inputs = ['Tom', 'Tom', 'David', 'David', 'Vincent', 'Sam', 'Peter']

len([x for x in my_inputs if x in seek]) // 4

EDIT : although it shows how powerful list comprehensions in python are, but requires extra-space (O(N) where N is len(my_inputs)) whereas Barmar's solution requires O(1) extra-space, so you'd probably be better off with Barmar's answer.

Hello dear @tse chun hei!

An elegant and effient way of doing it is through numpy:

inputs = ['Tom','David','David','Vincent','Sam']
items = ['Peter','Tom','Vincent']

You can then combine np.isin() with np.sum() and get your output with one line of code:

np.sum(np.isin(inputs,items))
2

I hope this post was usefull!

Best Regards,

You could also use the Counter in the collections module for this:

from collections import Counter
all_items = Counter(['Tom', 'David', 'David', 'Vincent', 'Sam'])

Counter is a subclass of dict . The all_items counter will look like this:

Counter({'Tom': 1, 'David': 2, 'Vincent': 1, 'Sam': 1})

You could then get the count of a key that you pass like this:

all_items.get('Tom') 

Output: 1

all_items.get('David')

Output: 2

To get multiple items, you could do the following:

items_to_check = ['Peter', 'Tom', 'Vincent'] # your list of multiple items to check

for item in items_to_check:
    print(f"Item: {item} \t Count: {all_items.get(item)}")

Output:

Item: Peter      Count: None
Item: Tom        Count: 1
Item: Vincent    Count: 1

To get the sum:

sum([x[1] for x in all_items.items() if x[0] in items_to_check])

Output: 2

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