Python range()
时间:2020-02-23 14:43:12 来源:igfitidea点击:
Python range()函数是一个实用程序函数,用于生成数字列表。
生成的数字列表对于迭代逻辑很有用。
Python 范围()
如果您从一开始就遵循我们的教程,您可能会注意到我们已经多次使用python range函数。
基本上,Python range用于生成数字列表。
请注意,Python range函数不会返回列表,而是像列表一样。
Python range函数的基本结构如下。
range(n):这将生成一个从0到n的数字列表。
range(a,b):这将生成一个从a到b-1的数字列表。
range(a,b,c):这将生成一个从a到b-1的数字列表,步长为c。
请记住,range()
函数不会返回任何列表。
在下面的示例中,我们将看到。
# initialize a list from 0 to 5 init_list = [0, 1, 2, 3, 4, 5] # it will show you the type is 'list' print('Type of init_list is :', type(init_list)) # get the instance of range() function instance_range = range(1, 10) # it will show that the type is 'range' print("Type of instance_range is :", type(instance_range))
Python range()函数示例
Python范围函数可以给出许多示例。
您可以在代码的许多地方使用它。
假设您需要打印前1到n个奇数。
您可以使用python range函数轻松地做到这一点。
该代码将是;
# prompt for input num = int(input('Enter the max limit: ')); # so, generate list from 1 to num(inclusive) for i in range(1, num+1, 2): print(i, end=' ')
其中给定11作为输入,我们将得到以下输出
Enter the max limit: 11 1 3 5 7 9 11
使用Python range()遍历遍历列表
但是,您可以使用列表索引访问python列表。
在这种情况下,索引将由python range函数生成。
以下代码将帮助您清楚地理解这一点。
# initialize a list init_list = [1, 'abc', 23, 'def'] for i in range(len(init_list)): print(init_list[i])
以下代码的输出将是
1 abc 23 def
因此,这就是Python范围函数的全部。
大多数时候,python range函数与for循环一起使用并迭代列表。