[英]Python - Create a List Starting at a Given Value and End at Given Length
如何創建具有列表起始值和長度的列表。 例如,如果我想創建一個從長度為5的17開始的列表:
num_list = [17, 18, 19, 20, 21]
我嘗試了以下但是它沒有產生正確的結果
def answer(start, length):
id_arr = list(range(start, length))
print(id_arr)
answer(17, 10)
Output: []
我理解這個的原因是因為,在這種情況下,起始值是17,但是,它試圖以值10結束,從而創建一個空列表,那么如何使length
值成為列表的大小而不是列表的結束值?
范圍功能本身可以滿足您的需求。
range(starting value, endvalue+1, step)
所以你可以去range(17,22)
如果您編寫自定義函數,請轉到:
def answer(start, length):
id_arr = list(range(start, start+length))
print(id_arr)
answer(17, 5)
output :
[17, 18, 19, 20, 21]
在你的def
id_arr = list(range(start, start+length))
應該給你想要的結果
不是,第一個參數是下限,第二個參數是半開區間的上限。
list(range(10,20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
def answer(start, length):
id_arr = list(range(start, start+length))
print(id_arr)
answer(17, 5)
只是附加到列表直到范圍。
def answer(start,length):
anslist=[start]
for ans in range(length):
anslist.append(start+ans)
print anslist
Python中的內置范圍函數對於以列表形式生成數字序列非常有用。 如果我們在范圍內提供兩個參數第一個是起點,第二個是終點。 給定的端點永遠不是生成列表的一部分。 所以我們可以使用這個方法:
def answer(start, length):
id_arr = [list_items for list_items in range(start, start + length)]
print id_arr
answer (17, 5)
>> [17, 18, 19, 20, 21]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.