我是Python的初學者,我想聽聽你的意見,用一種更復雜的方式來寫下面的代碼。我希望代碼能夠遍歷整個串列(x)中的專案,計算每個專案出現的次數,并將輸出存盤在一個新的串列(z)中。以下是代碼(按原樣作業):
x = ["apple"/span>, "orange"/span>, "cherry"/span>, "apple"/span>]
def new_list(a)。
z=[]
for i in x:
y = x.count(i)
(z.append(y))
return z
print(new_list(x))
uj5u.com熱心網友回復:
我建議做一個串列理解:
我建議做一個串列理解。
>>> x = ["apple"/span>, "orange"/span>, "cherry"/span>, "apple"/span>]
>>> [x.count(val) for val in x]
[2, 1, 1, 2]
>>>
或者用map更好:
>>> [*map(x.count, x)]
[2, 1, 1, 2]
>>>
uj5u.com熱心網友回復:
使用list.count(),你的編程順序是O(n^2),使用Counter和hashhmap,你的程式員的順序是O(n)。
試試這個:
x = ["apple"/span>, "orange"/span>, "cherry"/span>, "apple"/span>]
[x.count(i) for i in x]
# [2,1,1,2]
或者使用Counter:
from collections import Counter
dct = Counter(x)
# Counter({'apple': 2, 'orange': 1, 'cherry': 1})
[dct[i] for i in x] 。
# [2, 1, 1, 2]/span>
檢查運行時間。(Counter比list.count())
uj5u.com熱心網友回復:
你可以在集合中使用計數器類。因此,在輸入串列上進行迭代,然后找到每個元素的計數。
from collections import Counter
x = ["蘋果", "桔子", "櫻桃", "蘋果"]
c = Counter(x)
print([c[item] for item in x] )
#[2, 1, 1, 2]
uj5u.com熱心網友回復:
嘗試使用計數器類:
從集合import Counter
x = ["foo"/span>, "bar"/span>, "foo"/span>, "foo"/span>]。
z = Counter(x)
print(z)
# Output: {"foo": 3, "bar": 1}
uj5u.com熱心網友回復:
你可以使用集合模塊的Counter子類:
from collections import Counter
x = ["蘋果", "桔子", "櫻桃", "蘋果"]
counter = Counter(x)
z = list(counter.values() )
print(z) #[2,1,1]
我沒有使用count,因為它可能對性能不利,這一點也被這個答案所指出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/309991.html
標籤:

