繁体   English   中英

For循环到列表推导

[英]For loops into List comprehensions

我想打印出现多次的任何数字。 如何将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() ,因为它默认为空白。

>>> from collections import Counter
>>> text = "4 8 0 3 4 2 0 3"
>>> counts = Counter(text.split())
>>> valid = [k for k in counts if counts[k] > 1]
>>> valid
['4', '0', '3']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM