在列表中查找相似项目,添加它们,然后将结果添加到另一个列表
Find similar items in list, add them and then add the result to another list
我有一个列表,我正在尝试查找相似的项目,将它们添加到临时列表,找到相似项目的总和,然后将该结果添加到另一个列表。我得到的结果是 [15,6] 以下但我期待得到 [20,12,16]?我似乎无法包含所有相似的数字,并且似乎无法让 for 循环包含相似项目的最后一个数字。到目前为止,请看一下下面的代码,有什么意见可以帮助吗?
start_list = [5,5,5,5,6,6,8,8]
temp_list = []
final_list = []
for i in range(len(start_list )-1):
if start_list [i] == start_list [i+1]:
temp_list.append(start_list [i])
else:
total = sum(temp_list)
final_list .append(total)
temp_list = []
print(final_list)
只需使用计数器:
from collections import Counter
start_list = [5,5,5,5,6,6,8,8]
c = Counter(start_list)
print([x*n for x, n in c.items()])
我有一个列表,我正在尝试查找相似的项目,将它们添加到临时列表,找到相似项目的总和,然后将该结果添加到另一个列表。我得到的结果是 [15,6] 以下但我期待得到 [20,12,16]?我似乎无法包含所有相似的数字,并且似乎无法让 for 循环包含相似项目的最后一个数字。到目前为止,请看一下下面的代码,有什么意见可以帮助吗?
start_list = [5,5,5,5,6,6,8,8]
temp_list = []
final_list = []
for i in range(len(start_list )-1):
if start_list [i] == start_list [i+1]:
temp_list.append(start_list [i])
else:
total = sum(temp_list)
final_list .append(total)
temp_list = []
print(final_list)
只需使用计数器:
from collections import Counter
start_list = [5,5,5,5,6,6,8,8]
c = Counter(start_list)
print([x*n for x, n in c.items()])