元组的特点:不可变的列表,但是可哈希的。
列表是不可哈希的。
元组创建及使用
使用()括起来或使用tuple()创建元组。
如果一个元组只有一个元素,其初始化时应该如下定义:
只有一个元素的元组,在括号里需要添加逗号,以表明是元组
t = (1,)
t
(1,)
type(t)
只有一个元素的元组,在括号里需要添加逗号,以表明是元组
t = (1,)
t
(1,)
type(t)
access tuple
print(“The number of seconds since midnight is”, \
(currentTime[0] * 3600 + currentTime[1] * 60 +
currentTime[2]))
[root@python ~]# python fig05_06.py
Enter hour: 3
Enter minute: 4
Enter second: 5
The value of currentTime is: (3, 4, 5)
The number of seconds since midnight is 11045
示例2:
[root@python ~]# cat fig05_07.py
aString = “abc”
aList = [ 1, 2, 3 ]
aTuple = “a”, “A”, 1
unpack sequences to variables
print(“Unpacking string…”)
first, second, third = aString
print(“String values:”, first, second, third)
print(“\nUnpacking list…”)
first, second, third = aList
print(“List values:”, first, second, third)
print(“\nUnpacking tuple…”)
first, second, third = aTuple
print(“Tuple values:”, first, second, third)
swapping two values
x = 3
y = 4
print(“\nBefore swapping: x = %d, y = %d” % (x, y))
x, y = y, x # swap variables
print(“After swapping: x = %d, y = %d” % (x, y))
[root@python ~]# python fig05_07.py
Unpacking string…
String values: a b c
Unpacking list…
List values: 1 2 3
Unpacking tuple…
Tuple values: a A 1
Before swapping: x = 3, y = 4
After swapping: x = 4, y = 3
元组常用方法
index(value) # 默认返回元组中第一次遇到value的索引(从左到右)
count(value) # 计算元组中value出现的次数
嵌套
转换:tuple()
元组切片操作
seq[start:end] => (start:end)
从左往右切片,所以start要小于end;否则将得到一个空列表
start超出索引范围从0开始,end超出范围到len(lst)结束
start为0时可以省略,end为-1时可以省略
lst = list(range(0, 10))
lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lst[2:5:2]
[2, 4]
lst[5:2-1]
[5, 4, 3]
当step为负数时,从后往前数,此时start应该小于end,否则返回空列表
lst[::-1] # 反转列表
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
lst[0::2]
[0, 2, 4, 6, 8]
lst[1::2]
[1, 3, 5, 7, 9]
命名元组
命名元组与元组类似,也是不可变的。
from collections import namedtuple
User = namedtuple(‘User’, [‘name’, ‘age’])
me = User(‘lavenliu’, 23)
print(me)
print(me.name)
print(me.age)
print(me[0])
print(me[1])
me.name = ‘taoqi’
结果为:
- lavenliu
- 23
- lavenliu
- 23
欢迎各位学习软件测试的和想转行的加群:599411652或者加q:3128744015