Python-创建以给定值开始并以给定长度结束的列表 [英] Python - Create a List Starting at a Given Value and End at Given Length

查看:62
本文介绍了Python-创建以给定值开始并以给定长度结束的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个具有起始值和列表长度的列表.例如,如果我要创建一个以17开始且长度为5的列表:

How can I create a list that will have a starting value and length of the list. For example, if I wanted to make a list starting at 17 that was of length 5:

num_list = [17, 18, 19, 20, 21]

我尝试了以下方法,但是无法产生正确的结果

I have tried the following however it is not producing the correct results

def answer(start, length):
id_arr = list(range(start, length))
print(id_arr)

answer(17, 10)

Output: []

我了解其原因,因为在这种情况下,起始值是17,但是它试图以值10结束,因此创建了一个空列表,因此我如何使length的值成为列表的大小而不是列表的结束值?

And I understand the reason for this because, the starting value, in this case, is 17, however, it is trying to end at value 10 thus creating an empty list so how can I make the value of length be the size of the list and not the ending value of the list?

推荐答案

范围函数本身会为您完成所有操作.

range function itself does all that for you.

range(starting value, endvalue+1, step)

所以你可以去range(17,22)

如果您编写自定义函数,请继续:

If you writing custom function then go for:

def answer(start, length):
    id_arr = list(range(start, start+length))
    print(id_arr)

answer(17, 5)

output :
[17, 18, 19, 20, 21]

这篇关于Python-创建以给定值开始并以给定长度结束的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆