假設我需要對一個串列進行排序,例如:
A=[1,1,1,1,1,1,1,0,0,0]
按照 4:1 的 1 和 0 之間的比率,得到A=[1,1,1,1,0,1,1,1,0,0].
那可能嗎?我嘗試以count這種方式使用命令:
scheme=[1,1,1,1,0,1,1,1,0,0]
for k, number in enumerate(scheme):
visited.append(number)
scheme[k] = visited.count(number)/len(scheme)
for z in scheme:
new = sorted(scheme).index(z)
final.append(sorted(que)[new])
但這不是一種舒適的方法scheme,因為指南串列在很大程度上取決于初始串列 A 的長度。
先感謝您!
uj5u.com熱心網友回復:
使用簡單的算術
假設序列只包含零和一。
from collections import Counter
def reorder_4_1(seq):
c = Counter(seq)
q1, r1 = divmod(c[1], 4)
diff = q1 - c[0]
if diff > 0:
return [1,1,1,1,0] * c[0] [1] * (diff r1)
else:
return [1,1,1,1,0] * q1 [1] * r1 [0] * (-diff)
print( reorder_4_1([1,1,1,1,1,1,1,0,0,0]) )
# [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
使用模塊itertools
roundrobin使用檔案中的itertools配方:
假設有兩組元素以 4:1 交錯
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
def interleave_4_1(a, b):
a = iter(a)
b = iter(b)
return roundrobin(a, a, a, a, b)
print(list( interleave_4_1([1,1,1,1,1,1,1],[0,0,0]) ))
# [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
假設序列保證是一和零的串列
from collections import Counter
from itertools import repeat
# def roundrobin...
def reorder_4_1(seq):
c = Counter(seq)
a = repeat(1, c[1])
b = repeat(0, c[0])
return roundrobin(a, a, a, a, b)
print(list( reorder_4_1([1,1,1,1,1,1,1,0,0,0]) ))
# [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
uj5u.com熱心網友回復:
這是一種沒有集合或 itertools 的方法,假設只有零和一,并且您首先想要一個,然后是零:
def ratio_sort(x,y,lst):
counter_dict = {1:0,0:0}
for num in lst: # count the amount of ones and zeroes in lst
counter_dict[num] =1
# find how many groups of ones and zeroes we have
one_groups = counter_dict[1]//x
zero_groups = counter_dict[0]//y
new_list = []
for i in range(min(one_groups, zero_groups)): # add ratios of ones and zeroes to new list
new_list.extend(([1]*x) ([0]*y))
counter_dict[1]-=x
counter_dict[0]-=y
new_list.extend(([1]*counter_dict[1]) ([0]*counter_dict[0])) # insert the leftovers
return new_list
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482216.html
上一篇:如何在不使用展開的情況下使用mongodb中的陣列元素對資料進行排序
下一篇:根據值和索引對熊貓系列進行排序
