簡體   English   中英

如何在Python中創建列表列表

[英]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 ,可以通過rangexrange函數來實現相同的目的。

您可以創建兩個range並將它們zip在一起:

def do_your_thing(start, end, step):
    return zip(range(start, end - step + 2, step),
               range(start + step - 1, end + 1, step))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM