元组总结

  • 元组是一种特殊的列表,不支持增删改,可通过索引,切片访问元组中的元素,也可通过for循环遍历所有元素,方法有两个:index()、count()
    • 索引访问元组元素,eg:
      test = (30, 5, 12, 23, 18, 45)
      result = test[2]
      print(result)

      输出:

      12
    • 通过切片访问元组元素,eg:
      test = (30, 5, 12, 23, 18, 45)
      result = test[2:-1]
      print(result)

      输出:

      (12, 23, 18)通过for循环遍历元组中元素,eg:
    • test = (30, 5, 12,)
      for result in test:
          print(result)

       输出:

      30
      5
      12
    • index():查找元素在元组中首次出现的索引,从左到右开始查找,如没有找到报错,eg:
      test = (30, 5, 12, 5, 56, 5,)
      result = test.index(5)
      print(result)

       输出:

      1
    • count():查找元素在元组中出现的次数,eg:
      test = (30, 5, 12, 5, 56, 5,)
      result = test.count(5)
      print(result)

       输出:

      3
    • 元组有一个特别需要主要的地方是,如果元组中只有一个元素,且这个元素是数字,则必须在元素后添加一个英文逗号,否则会被认为是int类型,而不是tuple类型,eg:
      test1 = (30)
      test2 = (30,)
      print(type(test1), type(test2), sep="\n")

       输出:

      <class 'int'>
      <class 'tuple'>

猜你喜欢

转载自www.cnblogs.com/xieliuxiang/p/9235912.html