[英]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.