元组

2018-08-07  本文已影响0人  __construct

与列表的区别

都是有序的集合

元组的操作

创建元组

tuple1 = ()
tuple2 = tuple()

基本操作

tuplue1 = ('a', 'b', 'c', 'd')
print(tuplue1[0])
# a
tuplue1 = ('a', 'b', 'c', 'd')
del tuplue1
print(tuplue1)
# NameError: name 'tuplue1' is not defined, 删除成功
tuplue1 = ('a', 'b', 'c', 'd')
tuplue2 = (1, 2, 3)

print(tuplue1 + tuplue2)
# ('a', 'b', 'c', 'd', 1, 2, 3)
tuplue1 = ('a', 'b', 'c', 'd')
print(tuplue1 *3)
# ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')
tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print(tuplue1[0:5])
# ('h', 'e', 'l', 'l', 'o')
tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print('h' in tuplue1) # True
print(1 in tuplue1)  # False

序列函数

tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print(len(tuplue1))
# 10 
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
print(max(tuple1))  # 9
print(min(tuple1))  #  0
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
for item in tuple1:
    print(item)

元组内涵/元组推导式

tuplue1 = ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')

t = (i for i in tuplue1)  # 结果为一个生成器
print(next(t)) # h
上一篇 下一篇

猜你喜欢

热点阅读