zoukankan      html  css  js  c++  java
  • 练习32--循环和列表

    一 相关知识

    1 range()函数

    • 功能:python range() 函数可创建一个整数列表,一般用在 for 循环中。
    • 语法:range(start, stop[, step])
    • 参数说明:
      • start: 计数从 start 开始。默认是从 0 开始。
      • stop: 计数到 stop 结束,但不包括 stop。
      • step:步长,默认为1。

    2 for循环

    • 功能:Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
    • 语法:
    for iterating_var in sequence:
      statements(s)
    • 其中iterating_var是用来表示被遍历序列中的元素;sequence表示被遍历序列;statements表示遍历过程中要执行的语句。

    3 append()方法

    • 功能:在列表末尾添加一个新的对象
    • 语法:list.append(obj)
    • 参数说明:
      • obj:表示要添加的对象
    • 返回值:该方法没有返回值,但是会修改原来的列表

    二 代码及执行结果

    ex32.py文件

     1 the_count = [1,2,3,4,5]
     2 fruits = ['apples','oranges','pears','apricots']
     3 changes = [1,'pennies',2,'dimes',3,'quarters']
     4 
     5 # this first kind of for-loop goes through a list
     6 for number in the_count:
     7     print(f"This is count {number}")
     8 
     9 # same as above
    10 for fruit in fruits:
    11     print(f"A fruit of type:{fruit}")
    12 
    13 # also we can go through mixed lists too 
    14 # notice we have to use {} since we don't know what's in it
    15 for i in changes:
    16     print(f"I got{i}")
    17 
    18 # we can also build lists,first start with an empty one
    19 elements = []
    20 
    21 # then use the range function to do 0 to 5 counts
    22 for i in range(0,6):
    23     print(f"Adding {i} to the list.")
    24     # append is a function that lists understand
    25     elements.append(i)
    26 
    27 # now we can print them out too
    28 for i in elements:
    29     print(f"Element was: {i}")

    执行结果:

    PS E:3_work4_python2_code_python2_LearnPythonTheHardWay> python ex32.py
    This is count 1
    This is count 2
    This is count 3
    This is count 4
    This is count 5
    A fruit of type:apples
    A fruit of type:oranges
    A fruit of type:pears
    A fruit of type:apricots
    I got1
    I gotpennies
    I got2
    I gotdimes
    I got3
    I gotquarters
    Adding 0 to the list.
    Adding 1 to the list.
    Adding 2 to the list.
    Adding 3 to the list.
    Adding 4 to the list.
    Adding 5 to the list.
    Element was: 0
    Element was: 1
    Element was: 2
    Element was: 3
    Element was: 4
    Element was: 5

    三 一些问题

    1、如何创建一个二维列表? 可以用这种列表中的列表: [[1,2,3],[4,5,6]]

    2、列表(lists)和数组(arrays)难道不是一个东西吗? 这取决于语言以及实现方法。在传统术语中,列表和数组的实现方式不同。在 Ruby 中都叫做 arrays,在 python 中都叫做 lists。所以我们就把这些叫做列表吧。

    3、为什么 for-loop可以用一个没有被定义的变量?变量在 for-loop 开始的时候就被定义了,它被初始化到了每一次 loop 迭代时的当前元素中。

  • 相关阅读:
    MySQL存储引擎--MyISAM与InnoDB区别
    HTTP Keep-Alive模式
    php通过curl下载远程图片实例
    使用PHP QR Code生成二维码
    PHP中输出文件,怎么区别什么时候该用readfile() , fread(), file_get_contents(), fgets()
    SSDB 一个高性能的支持丰富数据结构的 NoSQL 数据库, 用于替代 Redis.
    html头文件设置常用之<meta>设置缓存
    redis使用watch完成秒杀抢购功能
    Linux信号(signal) 机制分析
    php信号处理
  • 原文地址:https://www.cnblogs.com/luoxun/p/13307180.html
Copyright © 2011-2022 走看看