• 技术文章 >Python技术 >Python基础教程

    python中数字列表的详细介绍

    silencementsilencement2019-06-28 09:50:52原创3168

    数字列表和其他列表类似,但是有一些函数可以使数字列表的操作更高效。我们创建一个包含10个数字的列表,看看能做哪些工作吧。

    1

    2

    3

    4

    5

    # Print out the first ten numbers.

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

     

    for number in numbers:

        print(number)

    range() 函数

    普通的列表创建方式创建10个数是可以的,但是如果想创建大量的数字,这种方法就不合适了。range() 函数就是帮助我们生成大量数字的。如下所示:

    1

    2

    3

    # print the first ten number

    for number in range(1, 11):

        print(number)

    range() 函数的参数中包含开始数字和结束数字。得到的数字列表中包含开始数字但不包含结束数字。同时你也可以添加一个 step 参数,告诉 range() 函数取数的间隔是多大。如下所示:

    1

    2

    3

    # Print the first ten odd numbers.

    for number in range(1,21,2):

        print(number)

    如果你想让 range() 函数获得的数字转换为列表,可以使用 list() 函数转换。如下所示:

    1

    2

    3

    # create a list of the first ten numbers.

    numbers = list(range(1,11))

    print(numbers)

    这个方法是相当强大的。现在我们可以创建一个包含前一百万个数字的列表,就跟创建前10个数字的列表一样简单。如下所示:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    # Store the first million numbers in a list

    numbers = list(range(1,1000001))

     

    # Show the length of the list

    print("The list 'numbers' has " + str(len(numbers)) + " numbers in it.")

     

    # Show the last ten numbers.

    print("\nThe last ten numbers in the list are:")

    for number in numbers[-10:]:

        print(number)

    min(), max() 和 sum() 函数

    如标题所示,你可以将这三个函数用到数字列表中。min() 函数求列表中的最小值,max() 函数求值,sum() 函数计算列表中所有数字之和。如下所示:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    ages = [23, 16, 14, 28, 19, 11, 38]

     

    youngest = min(ages)

    oldest = max(ages)

    total_years = sum(ages)

     

    print("Our youngest reader is " + str(youngest) + " years old.")

    print("Our oldest reader is " + str(oldest) + " years old.")

    print("Together, we have " + str(total_years) +

          " years worth of life experience.")

    专题推荐:数字列表
    上一篇:Python新手常见问题四:误用Python作用域的规则 下一篇:Python新手常见问题七:循环加载模块

    相关文章推荐

    • Python实现的简易FTP• python新手常见问题一:乱用表达式

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网