简体   繁体   中英

How do I compare numbers and find how many numbers are matched inside a list on Python?

I have a list:

a = [3, 4, 5, 2, 3]

How do I get how many numbers are matched inside this list?

I guess you want to find how many duplicates you have in your list.

listItem = [3, 4, 5, 2, 3]
s = set([x for x in listItem if listItem.count(x) > 1])  # -> {3}
n_duplicates = len(s)  # -> 1

here is the way to prepare special dictionary {value: how_many_times_matched}

 cnt = {k:listItem.count(k) for k in set(listItem)}

 Out[1]:
      {2: 1, 3: 2, 4: 1, 5: 1}


 mtch = {k:v for k,v in cnt.items() if v>1}

 Out[2]:
      {3: 2}

if you know exactly the num

 listItem.count(3)

 Out[3]:
 2

I am not sure what your end game is with the information of matches. But to strictly get the answer you listed in your comments this is the simplest way. Look through the other answers as they may be more helpful depending on what you will be doing with the match information.

a = [3, 4, 5, 2, 3]
a_with_matches = [x for x in a if a.count(x) > 1]
len(a_with_matches)

#outputs:
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