python tuple
1 # tuple中的元素无法修改(但如果元素是列表则可以修改)
2
3 # 创建空tuple
4
5 tuple_empty = ()
6
7 # 创建只含有一个元素的tuple
8 tuple_first = ("ok",)
9
10
11 # 获取tuple中的值
12 tuple_first = ("ok", 123, "hello")
13 print(tuple_first[0])
14
15
16 # 统计元素个数
17 print(len(tuple_first))
18
19 # 统计元素出现次数
20 print(tuple_first.count("hello"))
21
22 # 获取元素索引
23 print(tuple_first.index("hello"))
24
25
26 # 遍历
27 for s in tuple_first:
28 print(s)
29
30 # list与tuple互转
31 myList = list(tuple_first)
32
33 print(myList)
34
35 newList = ["ok", "hello"]
36
37 myTuple = tuple(newList)
38 print(myTuple)
39
40 # 省略()的元组
41 a = 1, 2
42
43 a = 100
44 b = 20
45
46 # 利用元组交换变量的值
47 a, b = b, a