简体   繁体   中英

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 ?

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

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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