zoukankan      html  css  js  c++  java
  • Python之range()函数

    参考来源:

    https://realpython.com/python-range/

    1. Python range() 函数可创建一个整数列表,一般用在for循环中。

    三种方法可以调用range()。

    (1) range(stop) :输出从0开始到stop-1的整数。

    for i in range(3):
        print(i)
    
    #output
    #0
    #1
    #2

    (2) range(start, stop)

    for i in range(1, 8):
        print(i)
    
    #output
    #1
    #2
    #3
    #4
    #5
    #6
    #7

    3.range(start, stop, step),如果没有step, 默认step=1,且step可正可负,但不能为0。

    >>> range(1, 4, 0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: range() arg 3 must not be zero

    (1)随着range()增加。

    for i in range(3,100,25):
        print(i)
    
    #output
    #3
    #28
    #53
    #78

    (2)随着range()减小

    for i in range(10, -6, -2):
        print(i)
    
    #output:
    #10
    #8
    #6
    #4
    #2
    #0
    #-2
    #-4

    4.list的reversed用法。

    for i in reversed(range(5)):
        print(i)
    
    #output
    #4
    #3
    #2
    #1
    #0

    5.高级用法。

    type(range(3))
    <class 'range'>
    #可以像List一样下标操作
    
    range(3)[1]
    #>>1
    range(3)[2]
    #>>2
    range(6)[2:5]
    #>>range(2,5)

    6. Numpy的arange()

    import numpy as np
    np.arange(0.3, 1.6, 0.3)
    #>>> np.arange(0.3, 1.6, 0.3)
    #array([ 0.3,  0.6,  0.9,  1.2,  1.5])

    但是如果print()每一行。

    import numpy as np
    
    for i in np.arange(0.3, 1.6, 0.3):
        print(i)
    
    #0.3
    #0.6
    #0.8999999999999999
    #1.2
    #1.5

    np.linspace(1,4,20)。给了1到20之间隔开的20个数。

     np.linspace(1,4,20)
    # array([ 1.        ,  1.15789474,  1.31578947,  1.47368421, 
    #1.63157895, 1.78947368, 1.94736842, 2.10526316,
    #2.26315789, 2.42105263, 2.57894737, 2.73684211,
    #2.89473684, 3.05263158, 3.21052632,3.36842105,
    #3.52631579, 3.68421053, 3.84210526, 4. ])
    np.linspace(1,4,4) # array([ 1., 2., 3., 4.])
    np.linspace(0,0.5,51)
    #array([ 0.  ,  0.01,  0.02,  0.03,  0.04,  0.05,  0.06,  0.07,  0.08,
    #       0.09,  0.1 ,  0.11,  0.12,  0.13,  0.14,  0.15,  0.16,  0.17,
    #       0.18,  0.19,  0.2 ,  0.21,  0.22,  0.23,  0.24,  0.25,  0.26,
    #       0.27,  0.28,  0.29,  0.3 ,  0.31,  0.32,  0.33,  0.34,  0.35,
    #       0.36,  0.37,  0.38,  0.39,  0.4 ,  0.41,  0.42,  0.43,  0.44,
    #       0.45,  0.46,  0.47,  0.48,  0.49,  0.5 ])
    The Safest Way to Get what you Want is to Try and Deserve What you Want.
  • 相关阅读:
    穷举
    菱形
    6.824 Lab 3: Fault-tolerant Key/Value Service 3A
    6.824 Lab 2: Raft 2C
    6.824 Lab 2: Raft 2B
    一文学会Rust?
    字符串相似度匹配
    解决gson解析long自动转为科学计数的问题
    commonJs requirejs amd 之间的关系
    关于package.json的理解
  • 原文地址:https://www.cnblogs.com/Shinered/p/9802469.html
Copyright © 2011-2022 走看看