gpt4 book ai didi

python - 按照元素的特定顺序对列表进行排序

转载 作者:行者123 更新时间:2023-12-05 04:29:15 26 4
gpt4 key购买 nike

假设我需要像这样对列表进行排序:

A=[1,1,1,1,1,1,1,0,0,0]

按照 1 和 0 之间的 4:1 的比例,得到 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 的长度。

提前致谢!

最佳答案

使用简单的算术

假设序列只包含 0 和 1。

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

使用来自 the itertools documentation 的配方 roundrobin :

假设有两组元素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]

假设序列保证是 1 和 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]

关于python - 按照元素的特定顺序对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72397003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com