我想通过在某些情况下使用单个循环来创建多个列表。我知道如何创建一个通过追加完成的列表,但是这里循环的所有结果都放在一个我不想要的列表中。假设我们对前100个数字运行循环,我想创建多个列表,其中第一个列表包含的数字直到5,第二个从6到10,第三个从11到15,依此类推。此代码仅适用于我创建的一个列表。
number = range(100)
first = []
for i in number:
first.append(i)
first
类似的东西:
l = []
for x in range(6, 102, 5):
l.append([y for y in range(x-5, x)])
输出:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40],
[41, 42, 43, 44, 45],
[46, 47, 48, 49, 50],
[51, 52, 53, 54, 55],
[56, 57, 58, 59, 60],
[61, 62, 63, 64, 65],
[66, 67, 68, 69, 70],
[71, 72, 73, 74, 75],
[76, 77, 78, 79, 80],
[81, 82, 83, 84, 85],
[86, 87, 88, 89, 90],
[91, 92, 93, 94, 95],
[96, 97, 98, 99, 100]]
range
功能采用三个参数start
,stop
和step
。
尝试一下,这将创建您想要的东西:
lists = []
for i in range(1, 100, 5): # range(start, end, size_of_each_list)
lists.append(list(range(i,i + 5)))
lists
将是:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40],
[41, 42, 43, 44, 45],
[46, 47, 48, 49, 50],
[51, 52, 53, 54, 55],
[56, 57, 58, 59, 60],
[61, 62, 63, 64, 65],
[66, 67, 68, 69, 70],
[71, 72, 73, 74, 75],
[76, 77, 78, 79, 80],
[81, 82, 83, 84, 85],
[86, 87, 88, 89, 90],
[91, 92, 93, 94, 95],
[96, 97, 98, 99, 100]]
这是一种方法。基本上,您可以从列表中创建一个迭代器,然后从中获取所需的所有列表。
number = range(100)
number_iter = iter(number)
lists = []
while True:
try:
lists.append([next(number_iter) for _ in range(5)])
except StopIteration as e:
break
lists
这具有您的初始“号码”列表可以是任何东西的优点...
我会在第一个列表中使用第二个列表。
number = range(100)
cnt = 0
first = []
second = []
for i in number:
cnt += 1
second.append(i)
if cnt == 5:
first.append(second)
cnt = 0
second = []
first
输出:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
...
[95, 96, 97, 98, 99]]
我将执行类似于以下内容的列表理解:
[[i, i+1, i+2, i+3, i+4] for i in range (1, 100, 5)]
输出看起来像这样:
[[1, 2, 3, 4, 5],
...,
[96, 97, 98, 99, 100]]
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
可能。我们可以通过在globals()
环境中直接创建变量来做到这一点。(如果globals()
仅应包含在封闭函数中,则使用它。)>
您可以使用以下代码执行此操作:
locals()
此
locals()
首先:
# Run the loop
for i in range(100):
# for 0-4, list_name = 'list_1'
list_name = 'list_' + str(i//5 + 1)
# Try to append to that list
try:
globals()[list_name].append(i)
# If if doesn't exist, create it on the run!
except KeyError:
globals()[list_name] = [i]
变量。globals()[list_name] = [i]
的列表。让我们将它们全部打印出来:
list_name
您得到:
i
注意:为什么不开心一些!参见python
for i in range(20): # Print list_1 through list_20 list_name = 'list_' + str(i+1) print(list_name + ':', globals()[list_name])
包。