[英]Find sum of occurrence of elements in sliced-list mapped to index of element
我有以下列表:
my_list=['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']
我想創建一個新列表,用於計算my_list中迭代的my_list中所有出現的唯一值的總和。 迭代應從my_list中的第一項開始,並遍歷my_list中的所有項。
例如,我想要一個如下所示的列表:
[1, 2, 3, 4, 1, 2, 1, 2, 1]
您可以使用list.count()
來查找切片列表中單詞的出現以及列表理解 :
>>> my_list= ['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']
>>> [my_list[:i].count(name) for i, name in enumerate(my_list, 1)]
[1, 2, 3, 4, 1, 2, 1, 2, 1]
這里, my_list[:i].count(name)
將給予的發生的計name
在my_list
從0
到第i
個索引(在不包括值i
個索引)。 要了解enumerate()
,請參閱文檔 。 我用enumerate傳遞start = 1
,這意味着i
值將從1
開始。
與切片和計數相關的示例:
>>> my_list[:6] # Values upto `5`th index
['John', 'John', 'John', 'John', 'Joe', 'Joe']
>>> my_list[:6].count('John') # occurence of `John` in the list
4
編輯:此列表推導表達式與for
循環的等效轉換將是:
my_count = [] # v Means index `i` starting from `1`
for i, name in enumerate(my_list, 1):
word_count = my_list[:i].count(name)
my_count.append(word_count)
這里my_count
將保持由列表推導重新調整的相同值。
一種方法是構建一個Counter
,同時在列表的每次迭代中生成計數:
from collections import Counter
def stepped_counter(sequence):
seen = Counter()
for item in sequence:
seen[item]+=1 #add in the item
yield seen[item] #generate the current count of this item
>>> my_list= ['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']
>>> list(stepped_counter(my_list))
[1, 2, 3, 4, 1, 2, 1, 2, 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.