Python - 对连续元素重新排序
给定一个 List 执行重新排序以获得连续的相似元素。
Input : test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Output : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]
Explanation : All similar elements are assigned to be consecutive.
Input : test_list = [4, 7, 5, 1, 4, 1, 6, 7, 5]
Output : [4, 4, 7, 7, 5, 5, 1, 1, 6]
Explanation : All similar elements are assigned to be consecutive.
方法 #1:使用 Counter() + loop + items()
在这里,我们使用 Counter() 来执行计算频率的任务,并且使用 loop 和 items() 分别根据计数和访问频率对元素进行重新排序。
Python3
# Python3 code to demonstrate working of
# Reorder for consecutive elements
# Using Counter() + loop + items()
from collections import Counter
# initializing list
test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
# printing original lists
print("The original list is : " + str(test_list))
# getting frequency
freqs = Counter(test_list)
res = []
# reordering basis of frequency
for val, cnt in freqs.items():
res.extend([val]*cnt)
# printing result
print("Reordered List : " + str(res))
Python3
# Python3 code to demonstrate working of
# Reorder for consecutive elements
# Using Counter() + elements()
from collections import Counter
# initializing list
test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
# printing original lists
print("The original list is : " + str(test_list))
# reordering using elements()
res = list(Counter(test_list).elements())
# printing result
print("Reordered List : " + str(res))
输出:
The original list is : [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Reordered List : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]
方法#2:使用 Counter() + elements()
在这里,我们使用 elements() 执行重新排序计数频率的任务,提供简洁的解决方案。
蟒蛇3
# Python3 code to demonstrate working of
# Reorder for consecutive elements
# Using Counter() + elements()
from collections import Counter
# initializing list
test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
# printing original lists
print("The original list is : " + str(test_list))
# reordering using elements()
res = list(Counter(test_list).elements())
# printing result
print("Reordered List : " + str(res))
输出:
The original list is : [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Reordered List : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]