生成一个包含两个变量名、41个索引长的列表,其中同一变量的长度不超过三个

2024-09-24 02:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要生成两个变量名(大和小)的列表。这个列表需要有41个索引长,在小变量和大变量之间提供40个索引转换。没有一个变量可以连续重复三次以上。因此,每个列表应该包含四种过渡类型的10个表示:小-小、大-大、小-大、大-小。例如:

>>> large = 5

>>> small = 10

>>> L1 = [large, large, small, small, large, large, small, small, small, large, small, large, large, large, small, large, large, small, large, small, small, large, large, large, small, small, large, large, small, small, small, large, large, small, small, large, small, small, large, large, small]

我最终需要创建10个这种列表的变体

到目前为止,我使用的代码是:

import random

S = 5
L = 10
Ratios = [S, L]

Master_List = []

def ListGenerator(List1, List2):
    GeneratedList = []
    random.shuffle(List1)
    for i in List1:
        if len(GeneratedList) < 41:
            GeneratedList.append(i)
        elif len(GeneratedList) == 41:
            break

    for i in GeneratedList:
        List2.append(i)

    return List2


print ListGenerator(Ratios, Master_List)

具体问题

为什么我当前的代码只返回两个元素的列表,如何评估是否满足列表条件,以便创建无序变量列表


Tags: 代码inmaster列表forlenrandomlist