码迷,mamicode.com
首页 > 其他好文 > 详细

元组总结

时间:2018-06-27 22:28:25      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:IV   支持   英文   索引   count   result   报错   for循环   开始   

  • 元组是一种特殊的列表,不支持增删改,可通过索引,切片访问元组中的元素,也可通过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>

       

       

元组总结

标签:IV   支持   英文   索引   count   result   报错   for循环   开始   

原文地址:https://www.cnblogs.com/xieliuxiang/p/9235912.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!