以下是一个示例代码,可以将列表中的元素按组计数并分配给新的变量:
# 原始列表
original_list = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
# 使用字典来计数
count_dict = {}
for element in original_list:
if element in count_dict:
count_dict[element] += 1
else:
count_dict[element] = 1
# 打印计数结果
for element, count in count_dict.items():
print(f"{element}: {count}")
# 分配给新变量
grouped_list = []
for element, count in count_dict.items():
grouped_list.extend([element] * count)
print(grouped_list)
输出结果为:
1: 2
2: 1
3: 3
4: 1
5: 4
[1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 5]
以上代码首先使用字典来计数每个元素的出现次数,然后打印计数结果。接着,使用extend
方法根据计数结果,将每个元素按照对应次数添加到新的列表中。最后,打印新的列表。
上一篇:按组进行指数加权函数