[英]How to create a list of lists in Python
我有一個起點和終點,我想創建一個像這樣的列表(起點= 0,終點= 300,台階= 100):
[[1, 100], [101, 200], [201, 300]]
開始,結束和步驟會有所不同,因此我必須動態創建列表。
>>> start = 0
>>> end = 300
>>> step = 100
>>> [[1 + x, step + x] for x in range(start, end, step)]
[[1, 100], [101, 200], [201, 300]]
您只需要一個簡單的while循環:-
start = 0
end = 300
step = 100
my_list = []
while start < end: # Loop until you reach the end
my_list.append([start + 1, start + step])
start += step # Increment start by step value to consider next group
print my_list
輸出:-
[[1, 100], [101, 200], [201, 300]]
在list comprehension
,可以通過range
或xrange
函數來實現相同的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.