列表理解而不是重复数字列表的嵌套循环

List Comprehension Instead of Nested For Loops for Repeated Number List

我想创建一个脚本,在两个变量 (First_Number, Last_Number) 之间创建一个值列表,其中每个数字重复 Repeat_Count 次。我编写了一个嵌套 for 循环的脚本来执行此操作。我想通过列表理解来做到这一点,但不知道是否可行。

First_Number = 1
Last_Number = 10
Repeat_Count = 5

MyList = []
for numbers in range(First_Number,Last_Number - First_Number + 2):
    for repeated_number in range(0,Repeat_Count):
        MyList.append(numbers)

print MyList

输出:

[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10]

你可以这样做:

[x for x in xrange(First_Number, Last_Number+1) for y in xrange(Repeat_Count)]
from itertools import chain
list(chain(*[[i]*repeat_count for i in range(first_number, last_number+1)]))

chain 将展平数组:[[1, 1], [2, 2]] => [1, 1, 2, 2]

[i]*repeat_count 是生成 [i, i, i, ... , i]

的好方法

此外,一般规则是将变量命名为小写。

你可以用 pythonic 的方式来做

>>> first_num = 1
>>> last_num = 10
>>> repeat_no = 5
>>> mylist = []
>>> [mylist.extend([num]*repeat_no) for num in range(first_num, last_num + 1)]
>>> mylist
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10]