所以我撰寫了這段代碼來列印一個數字在我提供的串列中列印多少次,并且輸出有效,但是我想把我得到的所有值都放到一個串列中,我該怎么做?這是我的代碼...
i = [5,5,7,9,9,9,9,9,8,8]
def num_list(i):
return [(i.count(x),x) for x in set(i)]
for tv in num_list(i):
if tv[1] > 1:
print(tv)
我得到的輸出是
(2, 8)
(5, 9)
(2, 5)
(1, 7)
但我希望輸出像
[2,8,5,9,2,5,1,7)
我怎樣才能做到這一點??
uj5u.com熱心網友回復:
做就是了:
tvlist = []
for tv in num_list(i):
if tv[1] > 1:
tvlist.extend(tv)
print(tvlist)
或串列理解:
tvlist = [x for tv in num_list(i) if tv[1] > 1 for x in tv]
您的功能也可以只是collections.Counter:
from collections import Counter
def num_list(i):
return Counter(i).items()
uj5u.com熱心網友回復:
flattened_iter = itertools.chain.from_iterable(num_list(i))
print(list(flattened_iter))
是我如何將串列展平
正如其他人所提到的 collections.Counter 可能會顯著提高大型串列的性能......
如果你寧愿自己實作它,你可以很容易地
def myCounter(a_list):
counter = {}
for item in a_list:
# in modern python versions order is preserved in dicts
counter[item] = counter.get(item,0) 1
for unique_item in counter:
# make it a generator just for ease
# we will just yield twice to create a flat list
yield counter[unique_item]
yield unique_item
i = [5,5,7,9,9,9,9,9,8,8]
print(list(myCounter(i)))
uj5u.com熱心網友回復:
使用 acollections.Counter更有效。這配對itertools.chain將得到你想要的結果:
from collections import Counter
from itertools import chain
i = [5,5,7,9,9,9,9,9,8,8]
r = list(chain(*((v, k) for k, v in Counter(i).items() if v > 1)))
print(r)
[2, 5, 5, 9, 2, 8]
沒有 itertools.chain
r = []
for k, v in Counter(i).items():
if v > 1:
r.extend((v, k))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311495.html
上一篇:如何將物件轉換為集合?
下一篇:對串列中的元素進行分組
