如何比较数字并找到在Python列表中匹配的数字?

我有一个列表:

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

如何获取此列表中匹配的数字?

xifeng_pc 回答:如何比较数字并找到在Python列表中匹配的数字?

我猜您想查找列表中有多少重复项。

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

这是准备特殊词典{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}

如果您确切知道数字

 listItem.count(3)

 Out[3]:
 2
,

我不确定比赛信息会如何结束比赛。但是要严格获得您在评论中列出的答案,这是最简单的方法。查看其他答案,因为它们可能会对您有更多帮助,具体取决于您将要使用的匹配信息。

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

#outputs:
2
本文链接:https://www.f2er.com/3150825.html

大家都在问