For循环到List comprehensions

时间:2018-02-03 07:27:55

标签: python loops

我想打印出现不止一次的任何号码。如何将 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

2 个答案:

答案 0 :(得分:7)

而不是自己计算值:

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(),因为它默认为空格。

答案 1 :(得分:1)

>>> 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']