首页 > 其他 > 详细

基础数据类型-tuple

时间:2017-01-19 15:22:59      阅读:312      评论:0      收藏:0      [点我收藏+]

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

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

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

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

技术分享
 1 #索引
 2 tuple_number = (1, 2, 3, 4, 5)
 3 print("tuple_number[2]:", tuple_number[2])
 4 #切片
 5 print("tuple_number[1:4]:", tuple_number[1:4])#index = 4的元素不包含
 6 #检查成员
 7 if 6 in tuple_number:
 8     print("6 is in tuple_number")
 9 else:
10     print("6 is not in tuple_number")
11 #
12 tuple_name = (John, Paul)
13 print("tuple_number plus tuple_name:", tuple_number + tuple_name)
14 #
15 print("tuple_number * 2:", tuple_number * 2)
Code
技术分享
1 tuple_number[2]: 3
2 tuple_number[1:4]: (2, 3, 4)
3 6 is not in tuple_number
4 tuple_number plus tuple_name: (1, 2, 3, 4, 5, John, Paul)
5 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()

技术分享
1 #方法
2 tuple_number = (1, 1, 2, 2, 2, 3, 3, 3, 3)
3 print("count of 2 in tuple_number:", tuple_number.count(2)) #元素出现的次数
4 print("index of first 3:", tuple_number.index(3)) #元素第一次出现的位置
Code
技术分享
1 count 2 in tuple_number: 3
2 index of first 3: 5
Result

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

技术分享
 1 class tuple(object):
 2     """
 3     tuple() -> empty tuple
 4     tuple(iterable) -> tuple initialized from iterable‘s items
 5     
 6     If the argument is a tuple, the return value is the same object.
 7     """
 8     def count(self, value): # real signature unknown; restored from __doc__
 9         """ T.count(value) -> integer -- return number of occurrences of value """
10         return 0
11 
12     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
13         """
14         T.index(value, [start, [stop]]) -> integer -- return first index of value.
15         Raises ValueError if the value is not present.
16         """
17         return 0
Class Tuple

 

基础数据类型-tuple

原文:http://www.cnblogs.com/z-joshua/p/6306705.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!