「大数据」(一百二十五)Python基础之元组:tuple函数

【导读:数据是二十一世纪的石油,蕴含巨大价值,这是·情报通·大数据技术系列第[125]篇文章,欢迎阅读收藏】

1 基本概念

Python 的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

如下实例:

<code>tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"/<code>

元组的主要作用是作为参数传递给函数调用、或是从函数调用那里获得参数时,保护其内容不被外部接口修改。

「大数据」(一百二十五)Python基础之元组:tuple函数

元组包含了以下内置函数, tuple 函数是其中之一,可将列表转化为元组,也可作为创建元组的方法 。

1 、 cmp(tuple1, tuple2) 比较两个元组元素。

2 、 len(tuple) 计算元组元素个数。

3 、 max(tuple) 返回元组中元素最大值。

4 、 min(tuple) 返回元组中元素最小值。

5 、 tuple(seq) 将列表转换为元组。

2 详细说明

2.1 创建元组

<code># 不传入参数,创建空元组
>>> tuple()
()

# 传入不可迭代对象,不能创建新的元组
>>> tuple(121)  Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
tuple(121)
TypeError: 'int' object is not iterable

# 传入可迭代对象。使用其元素创建新的元组
>>> tuple('121')
('1', '2', '1')
>>> tuple([1,2,1])
(1, 2, 1)
>>> tuple((1,2,1))
(1, 2, 1)/<module>/<pyshell>/<code>

2.2 列表转化为元组

tuple() 方法语法:

tuple( seq ) ,参数 seq 为要转换为元组的序列,返回值为元组

以下实例展示了 tuple() 函数的使用方法。

实例 1 :

<code>>>> tuple ([ 1 , 2 , 3 , 4 ])
( 1 , 2 , 3 , 4 )
# 针对字典 会返回字典的 key 组成的 tuple
>>> tuple ( { 1 : 2 , 3 : 4 } )
( 1 , 3 )
# 元组会返回元组自身
>>> tuple (( 1 , 2 , 3 , 4 ))
( 1 , 2 , 3 , 4 )/<code>

实例 2 :

<code>#!/usr/bin/python
aList = [ 123 , ' xyz ' , ' zara ' , ' abc ' ] ;
aTuple = tuple ( aList )
print " Tuple elements : " , aTuple/<code>

以上实例的输出结果为:

<code>Tuple elements :  (123, 'xyz', 'zara', 'abc')/<code>


分享到:


相關文章: