python学习笔记------元组

元组的理解以及特性
# 列表: 打了激素的数组;
# 元组: 带了紧箍咒的列表,是不可变的;
names = ['a', 'b', 'c', 1, 1.5, [1, 2]]
tuple_names = (1, 1.5, 2 + 4j, "hello", [1, 2], 10)

print(type(names), type(tuple_names))

print(tuple_names.index(1))
print(tuple_names.count(1))

# 元组的特性:
# 索引, 切片, 连接, 重复, 成员操作符, for循环
print(tuple_names[0])
print(tuple_names[-1])
print(tuple_names[1:])
print(tuple_names[:-1])
print(tuple_names[::-1])
print(tuple_names + (1,2,43))

# 不同数据类型可以连接么?(除了数值类型之外, 不同数据类型之间不可以连接)
# print([1,2,3]+ (1,2,4))
# print('hello'+[1,2,3])
print(1+2+4j)

print(tuple_names*3)

print(1 in tuple_names)
print(1 not in tuple_names)

结果如下:

<class 'list'> <class 'tuple'>
0
1
1
10
(1.5, (2+4j), 'hello', [1, 2], 10)
(1, 1.5, (2+4j), 'hello', [1, 2])
(10, [1, 2], 'hello', (2+4j), 1.5, 1)
(1, 1.5, (2+4j), 'hello', [1, 2], 10, 1, 2, 43)
(3+4j)
(1, 1.5, (2+4j), 'hello', [1, 2], 10, 1, 1.5, (2+4j), 'hello', [1, 2], 10, 1, 1.5, (2+4j), 'hello', [1, 2], 10)
True
False
元组应用
# 元组应用的第一个场景:
x = 1
y = 2
x, y = y, x
# 1. 先把t = (y,x)封装为一个元组, 开辟了一个新的内存空间;
# 2. x = t[0] = 2
# 3. y = t[1] = 1
print(x,y)


# 2. 元组应用的第2个场景:
print("hello %s, hello %s" %("python", "c"))

t = ('python', 'c')
print("hello %s, hello %s" %t)

元组赋值给多个变量
# 元组的赋值
t = ('fentiao', 5, 18)
name, age, weight = t
print(name, weight,age )

scores = [100, 89, 90, 89, 67, 109]
# 列表的排序
scores.sort()
# python2中*middle是不能使用的;
min_score, *middle, max_score = scores
print("最终成绩为:%s" %(sum(middle)/4))


猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/81414121