Python中,元组tuple与list类似,不同之处在于tuple的元素不能修改,tuple使用(),list使用[],

(1)元组的创建使用(),需要注意的是创建包含一个元素的元组:

 tuple_number = ()
tuple_number = (1, ) #创建一个元素的元组,在元素后加逗号
print("type of (1) is:", type((1))) #(1)的类型是整形 type of (1) is: <class 'int'>

(2)元组的索引,切片,检查成员,加,乘

 #索引
tuple_number = (1, 2, 3, 4, 5)
print("tuple_number[2]:", tuple_number[2])
#切片
print("tuple_number[1:4]:", tuple_number[1:4])#index = 4的元素不包含
#检查成员
if 6 in tuple_number:
print("6 is in tuple_number")
else:
print("6 is not in tuple_number")
#加
tuple_name = ('John', 'Paul')
print("tuple_number plus tuple_name:", tuple_number + tuple_name)
#乘
print("tuple_number * 2:", tuple_number * 2)

Code

 tuple_number[2]: 3
tuple_number[1:4]: (2, 3, 4)
6 is not in tuple_number
tuple_number plus tuple_name: (1, 2, 3, 4, 5, 'John', 'Paul')
tuple_number * 2: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

Result

(3)tuple的遍历和list一样: for number in tuple_number:print(number)

(4)与list一样,tuple也有函数:len(),max(),min(),tuple()

(5)由于tuple的元素不允许修改,tuple的内置方法只有count(),index()

 #方法
tuple_number = (1, 1, 2, 2, 2, 3, 3, 3, 3)
print("count of 2 in tuple_number:", tuple_number.count(2)) #元素出现的次数
print("index of first 3:", tuple_number.index(3)) #元素第一次出现的位置

Code

 count 2 in tuple_number: 3
index of first 3: 5

Result

(6)最后看看tuple类的定义:

 class tuple(object):
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
"""
def count(self, value): # real signature unknown; restored from __doc__
""" T.count(value) -> integer -- return number of occurrences of value """
return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0

Class Tuple

最新文章

  1. ArcGIS ElementLayer上放置Windows控件
  2. 背景:表A数据误操作,被delete了,恢复。
  3. 2014年QS世界大学排名
  4. 【PHPsocket编程专题(实战篇③)】构建基于socket的HTTP请求类
  5. ios开发 数据库版本迁移手动更新迭代和自动更新迭代
  6. HDU 5501 The Highest Mark 背包dp
  7. JIRA Cannot Start Due to 'unable to clean the cache directory: /opt/jira/plugins/.osgi-plugins/felix'
  8. 怎么用visual studio2010编写c++程序|用visual studio2010编写c++程序的步骤
  9. android studio 环境配置
  10. cocos2d_x_06_游戏_一个都不能死
  11. I/O概述和审查操作
  12. 原生AJAX基础讲解及兼容处理
  13. 转:【Java并发编程】之十六:深入Java内存模型——happen-before规则及其对DCL的分析(含代码)
  14. Django Channels 入门指南
  15. python3 第二十八章 - 内置函数之List相关
  16. 朱晔和你聊Spring系列S1E10:强大且复杂的Spring Security(含OAuth2三角色+三模式完整例子)
  17. Post Tuned Hashing,PTH
  18. 【Acm】算法之美—Jugs
  19. struct timeval 计时问题
  20. Spark高级数据分析&#183; 2数据分析

热门文章

  1. swift实现一个对象池
  2. 初学JavaScript从入门到放弃(一)JavaScript介绍、变量、数据类型
  3. http请求常用的状态码
  4. mysql学习记录,CASE WHEN THEN ELSE END用法
  5. 前端优化:css雪碧图实践应用详解
  6. Linux phpmailer发送邮件失败的解决方法
  7. MapReduce输入输出的处理流程及combiner
  8. kubernetes资源清单定义
  9. consonant_摩擦音_咬舌音
  10. Redis- redis.conf