假设我需要对列表进行如下排序:

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

按照1和0之间4:1的比率,获得so A=[1,1,1,1,0,1,1,1,0,0].

这可能吗?

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,指南列表,强烈依赖于初始列表的长度.

提前感谢您!

推荐答案

使用简单算法

假设序列只包含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]

Using module 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相关问答推荐

使用pandas MultiIndex进行不连续 Select

telegram 机器人API setMyName不起作用

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

了解shuffle在NP.random.Generator.choice()中的作用

Twilio:CallInstance对象没有来自_的属性'

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

查找下一个值=实际值加上使用极点的50%

多处理代码在while循环中不工作

如何根据另一列值用字典中的值替换列值

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

为什么tkinter框架没有被隐藏?

删除最后一个pip安装的包

可变参数数量的重载类型(args或kwargs)

无法使用requests或Selenium抓取一个href链接

如何在Python数据框架中加速序列的符号化

如何从pandas的rame类继承并使用filepath实例化

使用密钥字典重新配置嵌套字典密钥名

在Python中调用变量(特别是Tkinter)

(Python/Pandas)基于列中非缺失值的子集DataFrame

在matplotlib中使用不同大小的标记顶部添加批注