我想打印出现不止一次的任何数字。如何将我的for 循环 更改为列表理解?
from collections import Counter
cnt=Counter()
in1="4 8 0 3 4 2 0 3".split(" ")
for elt in in1:
cnt[elt]+=1
more_than_one=[]
for value, amount in cnt.items():
if amount > 1: more_than_one.append(value)
print(*more_than_one)
理想的输出:4 0 3
请您参考如下方法:
与其自己计算值:
cnt=Counter()
in1="4 8 0 3 4 2 0 3".split(" ")
for elt in in1:
cnt[elt]+=1
您可以简单地将 in1 传递给 collections.Counter()为你做所有的计数:
cnt = Counter(in1)
至于把你的代码变成一个列表理解,你可以试试这个:
from collections import Counter
in1="4 8 0 3 4 2 0 3".split()
cnt = Counter(in1)
print([k for k, v in cnt.items() if v > 1])
哪些输出:
['4', '0', '3']
注意:您也不需要将 "" 传递给 split(),因为它默认为空白。
