[英]For loops into List comprehensions
I'd like to print any number that appears more than once. 我想打印出现多次的任何数字。 How do I change my 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)
Desirable output: 4 0 3 理想的输出:4 0 3
Instead of counting the values yourself: 不用自己计算值:
cnt=Counter()
in1="4 8 0 3 4 2 0 3".split(" ")
for elt in in1:
cnt[elt]+=1
You can simply pass in1
to collections.Counter()
to do all the counting for you: 您可以简单地将
in1
传递给collections.Counter()
来为您进行所有计数:
cnt = Counter(in1)
As for turning your code into a list comprehension, you can try this: 至于将代码转换为列表理解,您可以尝试以下方法:
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])
Which Outputs: 哪些输出:
['4', '0', '3']
Note: You also don't need to pass " "
to split()
, since it defaults to white space. 注意:您也无需将
" "
传递给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.