Python - 用频率和项目的乘积替换列表中相同的连续元素
给定一个列表,任务是编写一个Python程序,用频率和 Item 的乘积替换连续元素的分组。
Input : test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
Output : [12, 6, 7, 15, 16, 30, 3, 4]
Explanation : 3 occurs 4 times in consecution hence, 3*4 = 12, the result.
Input : test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5]
Output : [12, 6, 7, 15]
Explanation : 5 occurs 3 times in consecution hence, 5*3 = 15, the result.
方法一:使用循环。
在此,将元素与前一个元素进行比较以决定组结束,如果元素不同,则将计数与元素的乘积作为结果附加。
Python3
# Python3 code to demonstrate working of
# Equal Consecution Product
# Using loop
# initializing list
test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8,
8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
# printing original list
print("The original list is : " + str(test_list))
res = []
count = 1
for idx in range(1, len(test_list)):
# checking with prev element
if test_list[idx - 1] != test_list[idx]:
# appending product
res.append((test_list[idx - 1] * count))
count = 0
count += 1
res.append((test_list[-1] * count))
# printing result
print("Elements after equal Consecution product : " + str(res))
Python3
# Python3 code to demonstrate working of
# Equal Consecution Product
# Using groupby() + sum()
from itertools import groupby
# initializing list
test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
# printing original list
print("The original list is : " + str(test_list))
# creating Consecution groups and summing for required values
res = [sum(group) for k, group in groupby(test_list)]
# printing result
print("Elements after equal Consecution product : " + str(res))
输出:
The original list is : [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
Elements after equal Consecution product : [12, 6, 7, 15, 16, 30, 3, 4]
方法二:使用groupby() + sum()
在这种情况下,使用 groupby() 形成组,并且分组元素的总和给出所需的产品。
蟒蛇3
# Python3 code to demonstrate working of
# Equal Consecution Product
# Using groupby() + sum()
from itertools import groupby
# initializing list
test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
# printing original list
print("The original list is : " + str(test_list))
# creating Consecution groups and summing for required values
res = [sum(group) for k, group in groupby(test_list)]
# printing result
print("Elements after equal Consecution product : " + str(res))
输出:
The original list is : [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
Elements after equal Consecution product : [12, 6, 7, 15, 16, 30, 3, 4]