1.python中tuple和list的相互转换
if __name__ == '__main__':
# list to tuple
lis = [1, 2, 3, 4, 5, 6]
print(type(lis),lis)
x = tuple(lis)
print(type(x), x)
# tuple to list
tup = (1, 2, 3, 4, 5, 6)
print(type(tup), tup)
y = list(tup)
print(type(y), y)
结果:
<class 'list'> [1, 2, 3, 4, 5, 6]
<class 'tuple'> (1, 2, 3, 4, 5, 6)
<class 'tuple'> (1, 2, 3, 4, 5, 6)
<class 'list'> [1, 2, 3, 4, 5, 6]
2.如何对生成器类型的对象实现切片操作?
from itertools import islice
if __name__ == '__main__':
gen = iter(range(5)) # iter()函数用来生成一个迭代器对象
print(type(gen))
# param1迭代器,param2起始索引,param3结束索引
print(type(islice(gen, 0, 4)))
for i in islice(gen, 0, 4):
print(i)
3.将列表转为生成器
if __name__ == '__main__':
print([i for i in range(3)])
print((i for i in range(3)))
4.如何把字符串编码成 bytes 类型
if __name__ == '__main__':
#1
a = b'hello'
#2.
b = bytes("你好", "utf-8")
#3.
c = "你好".encode("utf-8")
print(a, type(a),b, c)
结果:
b'hello' <class 'bytes'> b'\xe4\xbd\xa0\xe5\xa5\xbd' b'\xe4\xbd\xa0\xe5\xa5\xbd'
5.元组a = (1, 2, 3)中的元素能不能修改(不能)
if __name__ == '__main__':
a = (1, 2, 3)
a[1] = 2
结果:TypeError: 'tuple' object does not support item assignment
6.元组a = (1, 2, [4 , 4 , 5])中的元素能不能修改(不一定)
if __name__ == '__main__':
#第一种(能),修改的是元组里面的列表元素
a = (1, 2, [4 , 4 , 5])
a[2][0] = 3
print(a)
结果:(1, 2, [3, 4, 5])
#第二种(不能),修改的是列表以外的元素
a[0] = 1
结果:TypeError: 'tuple' object does not support item assignment
来源:CSDN
作者:一个喜欢林俊杰的靓仔
链接:https://blog.csdn.net/qq_37680159/article/details/104474632