python基础第九章:元组

元组

声明一个空元组:

变量=() 或  变量=tuple()

声明有数据的元组

变量=(值,值……)或 变量=tuple(值,值……)

只有元组可以这么写

res=1,2,3
print(res)

基本操作
元组只能使用索引查看内容,不能进行增删改
res=(1,2,3,4,5)
print(res[0:])

元组只能删除整个元组,不能只删除元组的值
res=(1,2,3,4,5,6)
del res
print(res)

元组推导式 (注意:返回的是一个迭代器)
变量 = (变量 for 变量 in 元组)

查看迭代器里的值方法:
一:print(next())
二:list()
三:for……in

res=(x for x in range(5))
print(res) #迭代器
#方法一
# print(next(res))
# print(next(res))
#方法二
# print(list(res))
#方法三
for i in res:
print(i)

查看是否是迭代器的方法
res=(x for x in range(5))
from collections import Iterator
res=isinstance(res,Iterator)
print(res)

手写一个生成器 yield(写法类似于return)
def func():
print(1)
yield '第一次生成'
print(2)
yield '第二次生成'
res=func()
print(next(res))
print(next(res))

元组的相关函数:
index():获取指定的值在元组中的索引
count():统计指定值在元组出现的次数

元组的内置函数:
len() min() max() tuple()
元组运算符
+ * in not in
元组的遍历
for ……in 容器





猜你喜欢

转载自www.cnblogs.com/szc-boke/p/11244173.html