简体   繁体   English

如何将列表扩展到一定大小而不重复每个单独的列表元素 n 次?

[英]How to expand a list to a certain size without repeating each individual list elements that n-times?

I'm looking to keep the individual elements of a list repeating for x number of times, but can only see how to repeat the full list x number of times.我希望让列表的各个元素重复 x 次,但只能看到如何重复完整列表 x 次。

For example, I want to repeat the list [3, 5, 1, 9, 8] such that if x=12 , then I want to produce tthe following list (ie the list continues to repeat in order until there are 12 individual elements in the list:例如,我想重复列表[3, 5, 1, 9, 8]这样如果x=12 ,那么我想生成以下列表(即列表继续按顺序重复,直到有 12 个单独的元素在列表中:

[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]

I can do the below but this is obviously not what I want and I'm unsure how to proceed from here.我可以执行以下操作,但这显然不是我想要的,我不确定如何从这里开始。

my_list = [3, 5, 1, 9, 8]
x = 12

print(my_list * 12)
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5, 1, 9, 8]

Your code repeats list 12 times.您的代码重复列表 12 次。 You need to repeat list until length is matched.您需要重复列表直到长度匹配。 This can achieved using Itertools - Functions creating iterators for efficient looping这可以使用Itertools 实现 - 为高效循环创建迭代器的函数

from itertools import cycle, islice

lis = [3, 5, 1, 9, 8]
out = list(islice(cycle(lis), 12))
print(out)

Gives #给#

[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]

More pythonic #更多 pythonic #

Use a for loop to access each element in list and iterate over 'length' times.使用 for 循环访问列表中的每个元素并迭代“长度”时间。 Repeat Ith element you access through loop in same list until length matches.在同一列表中重复您通过循环访问的第Ith元素,直到长度匹配。

lis = [3, 5, 1, 9, 8]
length = 12

out = [lis[i%len(lis)] for i in range(length)]
print(out)

Gives ##给##

[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]

There are multiple ways to go about it.有多种方法go一下吧。 If x is the final length desired and lst is the list (please do not use list as a variable name because it overwrites the builtin list function), then you can do:如果x是所需的最终长度并且lst是列表(请不要使用list作为变量名,因为它会覆盖内置list函数),那么你可以这样做:

lst = (lst * (1 + x // len(lst)))[:x]

This multiplies the list by the smallest number needed to get at least N elements, and then it slice the list to keep only the first N. For your example:这会将列表乘以至少获得 N 个元素所需的最小数字,然后将列表切片以仅保留第一个 N。对于您的示例:

>>> lst = [3, 5, 1, 9, 8]
>>> x = 12
>>> (lst * (1 + x // len(lst)))[:x]
[3, 5, 1, 9, 8, 3, 5, 1, 9, 8, 3, 5]

You could also use a loop, for example:您还可以使用循环,例如:

index = 0
while len(lst) < x:
    lst.append(lst[index])
    index += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM