Home >Backend Development >Python Tutorial >How to use Python's range function
The range() function is a built-in function of python. It can return a series of consecutively added integers and can generate a list object.
Most of them often appear in for loops and can be used as indexes in for loops.
Quick question practice: for..range practice
1: Use for loop and range to find all even numbers within 0 ~ 100, and append them to a list.
list1 = [] for i in range(0,100,2): list1.append(i) print(list1)
2: Use for loop and range to find the number within 0 ~ 50 that can be divided by 3, and append it to a list.
list2 = [] for j in range(0,50): if j%3 ==0: list2.append(j) print(list2)
3: Use for loop and range to find the number that is divisible by 3 within 0 ~ 50, and insert it into the 0th index position of the list. The final result is as follows: [48,45,42.. .]
list3 = [] for k in range(0,50): if k%3 == 0: list3.insert(0,k) print(list3)
4: Find the elements in the list li, remove the spaces before and after each element, and find the elements starting with "a", add them to a new list, and finally print the new list in a loop list.
li = ["alexC", "AbC ", "egon", " riTiAn", "WuSir", " aqc"]''' li = ["alexC", "AbC ", "egon", " riTiAn", "WuSir", " aqc"] li1 = [] for m in li: b = m.strip().startswith('a') if b == True : li1.append(m.strip()) for n in li1: print(n)
range(start, stop [,step])
Parameter introduction:
start refers to the starting value of counting and can be omitted If not written, the default is 0;
stop refers to the end value of the count, but does not include stop;
step is the step size, the default is 1 and cannot be 0.
(Special note: if there are three parameters, then the last parameter is expressed as the step size.)
ps1: Only one parameter : Indicates all integers from 0 to this parameter, excluding the parameter itself
ran = range(6) # 定义一个list,将range范围内的数都存入list arry_list = list(ran) print(ran) print(arry_list) #运行结果如下 range(0, 6) [0, 1, 2, 3, 4, 5]
ps2:
When the range function has 2 parameters, the first parameter represents Left boundary, the second parameter represents the right boundary, including left but not right.
ran_new = range(1, 8) list_one = list(ran_new) # 将range范围内的数据都存入list print(list_one) #运行结果 [1, 2, 3, 4, 5, 6, 7]
ps3: When
range contains 3 parameters, the first one represents the left boundary, the second represents the right border, and the third represents the step size. , that is, the difference between two integers, including the left but not the right.
# range含有3个参数时,第一个表示左边界,第二个表示右边界,第三个表示步长step,即两个整数之间相差的数,含左不含右 ran_two = range(1, 16,2) list_two = list(ran_two) # list_two= print(ran_new) print(ran_two) print(list_two)
The running result is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 , 13, 14, 15]
range(1, 16)
range(1, 16, 2)
[1, 3, 5, 7, 9, 11, 13, 15]
Example:
print("实例一:起始值为1,结束值为10") for i in range(1,10): print(i,end='') print("\n实例二:结束值为10") for i in range(10): print(i,end='') print("\n实例三:结束值为10,步长为2") for i in range(1,10,2): print(i,end='')
Run result:
Example 1: The starting value is 1, the ending value is 10123456789 Example 2: The end value is 100123456789 Example 3: The end value is 10, the step size is 213579
(1) Error reporting: TypeError: ‘list&rsquo ; object is not callable.
refers to the error type: The "list" object cannot be called
Reason:
Since the variable list and the function list have the same name, when the function uses the list function, it finds that list is a defined list, and the list cannot be called, so a type error is thrown. Therefore, when we define variables in the future, we should avoid duplication of function names, method names and keywords, as in any language.
(2) What if the range function reports an error:
TypeError: ‘float‘ object cannot be interpreted as an integer?
The reason is that range can only generate integers, not float types. Use numpy's arange function to solve the problem:
import numpy as np for i in np.arange(0.1,0.5,0.05): print(i) # 0.1,0.15,0.2,...,0.4,0.45, 不包含0.5! # 或者 l = list(np.arange(0.1,0.5,0.05))
① It represents an interval that is closed on the left and open on the right;
② The parameter it receives must be an integer, which can be a negative number, but cannot be a floating point number or other types;
'''判断指定的整数 在序列中是否存在 in ,not in''' print(10 in r) #False ,10不在当前的r这个整数序列中 print(9 in r) #true ,9在当前的这个r序列里 print(9 not in r) #false ,9不在当前的这个r序列里
③ It is immutable The sequence type can perform operations such as judging elements, finding elements, slicing, etc., but cannot modify elements;
④ It is an iterable object, but not an iterator.
# (1)左闭右开 >>> for i in range(3, 6):>>> print(i,end=" ")3 4 5 # (2)参数类型 >>> for i in range(-8, -2, 2):>>> print(i,end=" ")-8 -6 -4>>> range(2.2)----------------------------TypeError Traceback (most recent call last)...TypeError: 'float' object cannot be interpreted as an integer # (3)序列操作 >>> b = range(1,10)>>> b[0]1>>> b[:-3]range(1, 7)>>> b[0] = 2TypeError Traceback (most recent call last)...TypeError: 'range' object does not support item assignment # (4)不是迭代器 >>> hasattr(range(3),'__iter__')True>>> hasattr(range(3),'__next__')False>>> hasattr(iter(range(3)),'__next__')True
The official division is clear like this - there are three basic sequence types: list, tuple and range (range) object.
(There are three basic sequence types: lists, tuples, and range objects.)
The range type is a basic sequence in the same position as lists and tuples! What is the difference between range sequence and other sequence types?
Normal sequences support 12 operations, and range sequences only support 10 of them. Additive splicing and multiplication repetition are not supported.
>>> range(2) + range(3)-----------------------------------------TypeError Traceback (most recent call last)...TypeError: unsupported operand type(s) for +: 'range' and 'range' >>> range(2)*2-----------------------------------------TypeError Traceback (most recent call last)...TypeError: unsupported operand type(s) for *: 'range' and 'int'
Then the question arises: is also an immutable sequence. Why do strings and tuples support the above two operations, but range sequences do not?
Although immutable sequences cannot be modified directly, we can copy them to new sequences for operation. Why doesn’t the range object even support this?
Explanation from the official document:
...due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violates that pattern.
The reason is that the range object only represents a sequence that follows a strict pattern, and repetition and splicing usually violate this pattern...
问题的关键就在于 range 序列的 pattern!仔细想想,其实它表示的就是一个等差数列,拼接两个等差数列,或者重复拼接一个等差数列,这就是为啥 range 类型不支持这两个操作的原因了。因此可以得出结论,任何修改行为都会破坏等差数列的结构,因此最好不要进行任何修改。
【range类型的优点】
不管range对象表示的整数序列有多长,所有range对象占用的内存空间都是相同的,因为仅仅需要存储start、stop和step。只有当用到range对象时,才会去计算序列中的相关元素。
range函数实现逆序遍历两种实现方式
1)先创建一个列表,然后对列表中的元素进行逆序
例如:a=range(4)
a=range(4) # [0, 1, 2, 3]new =[]for i in reversed(a): new.append(i)print(new) # [3, 2, 1, 0]
2)直接使用range()函数完成逆序遍历
//第三个参数表示的是100所有进行的操作,每次加上-1,直到0for i in range(100,0,-1): print(i)
list1 = ["看不", "见你", "的", "笑", "我怎么", "睡", "得", "着"] for i in range(len(list1)): print(i, list1[i])
运行结果:
【range与list的区别】
range()是依次取顺序的数值,常与for循环一起用,如for范围内的每个(0, 5):for循环执行5次,每个取值是0〜4。而list()是把字符串转换为列表,如a = ’01234’ , b = list(a), a打印出来会是一个列表:[‘0’,‘1’,‘2’,‘3’,‘4’],如a = [0, 1, 2, 3, 4],输出的结果就会是[0, 1, 2, 3, 4]
#对比range与list for i in range(0, 5): print(i) a = [0, 1, 2, 3, 4] print(a)
(1)range对象的使用和理解都不难,但是在python的使用中非常常用!
(2)range对象既不是函数也不是迭代器,可以叫它“懒序列”;
(3)参数解释:start为范围开始,stop为范围结束,step为步长;
(4)range对象经常和for循环配合使用;
(5)可以对range对象进行索引;
关于range()函数还有一点需要注意的地方:range() 方法生成的只是可迭代对象,并不是迭代器!(Python2 中 range() 生成的是列表,本文基于Python3,生成的是可迭代对象)可以获得迭代器的内置方法很多,例如 zip() 、enumerate()、map()、filter() 和 reversed() 等等,但是像 range() 这样仅仅得到的是可迭代对象的方法就少有了。
在 for-循环 遍历时,可迭代对象与迭代器的性能是一样的,即它们都是惰性求值的,在空间复杂度与时间复杂度上并无差异。两者的差别概括是:相同的是都可惰性迭代,不同的是可迭代对象不支持自遍历(即next()方法),而迭代器本身不支持切片(即__getitem__() 方法)。虽然有这些差别,但很难得出结论说它们哪个更优。
那为什么给 5 种内置方法都设计了迭代器,偏偏给 range() 方法设计的就是可迭代对象呢?把它们都统一起来,不是更好么?事实上,Pyhton 为了规范性就干过不少这种事,例如,Python2 中有 range() 和 xrange() 两种方法,而 Python3 就干掉了其中一种。为什么不更规范点,令 range() 生成的是迭代器呢?
这个问题看到有大佬说的比较好的观点,这里引用一下:
zip() 等方法都需要接收确定的可迭代对象的参数,是对它们的一种再加工的过程,因此也希望马上产出确定的结果来,所以 Python 开发者就设计了这个结果是迭代器。
这样还有一个好处,即当作为参数的可迭代对象发生变化的时候,作为结果的迭代器因为是消耗型的,不会被错误地使用。
而 range() 方法就不同了,它接收的参数不是可迭代对象,本身是一种初次加工的过程,所以设计它为可迭代对象,既可以直接使用,也可以用于其它再加工用途。
例如,zip() 等方法就完全可以接收 range 类型的参数。
>>> for i in zip(range(1,6,2), range(2,7,2)):>>> print(i, end="")(1, 2)(3, 4)(5, 6)
也就是说,range() 方法作为一种初级生产者,它生产的原料本身就有很大用途,早早把它变为迭代器的话,无疑是一种画蛇添足的行为。重点不在于range对象是什么,而在于我们如何使用它
The above is the detailed content of How to use Python's range function. For more information, please follow other related articles on the PHP Chinese website!