Python的字符串,列表,字典,元组,集合之间的类型互转

字符串 与 列表(list) :

demo = '123'
l_demo = list(demo)
print(type(l_demo))
print(l_demo)

demo__ = (1,2,3)
l_demo__ = str(demo__)
print(type(l_demo__))
print(l_demo__)

结果:
<class 'list'>
['1', '2', '3']
<class 'str'>
(1, 2, 3)

字符串 与 元组(tuple) :

demo = '123'
l_demo = tuple(demo)
print(type(l_demo))
print(l_demo)

demo__ = (1,2,3)
l_demo__ = str(demo__)
print(type(l_demo__))
print(l_demo__)

结果:
<class 'tuple'>
('1', '2', '3')
<class 'str'>
(1, 2, 3)

字符串 与 字典(dict) :

# 字典可以转为字符串,反之不可

demo__ = {1:2,3:4}
l_demo__ = str(demo__)
print(type(l_demo__))
print(l_demo__)

结果:
<class 'str'>
{1: 2, 3: 4}

字符串 与 集合(set) :

demo = '1,2,3'
l_demo = set(demo)
print(type(l_demo))
print(l_demo)

demo__ = {1,3,4}
l_demo__ = str(demo__)
print(type(l_demo__))
print(l_demo__)

结果:
<class 'set'>
{'2', '3', '1', ','}
<class 'str'>
{1, 3, 4}

遍历:(除了for循环遍历)

1.对于字典类型,使用items()方法

a = {1:1,2:2}
for x,y in a.items():
    print(x,y)

结果:
1 1
2 2

2.对于可迭代对象还可以使用enumerate()方法  返回索引和值

a = [1,2,3]
for i in enumerate(a):
    print(i)

结果:
(0, 1)
(1, 2)
(2, 3)

3.同时遍历多个序列  可以使用 zip() 方法

a = [1,2,3]
b = [4,5,6]
for x,y in zip(a,b):
    print(x,'+', y)

结果:
1 + 4
2 + 5
3 + 6

4,反向遍历一个序列,可以使用 reversed() 方法

a = [1,2,3]
for i in reversed(a):
    print(i)

结果:
3
2
1

5,顺序遍历一个序列,可以使用sorted() 方法

a = [5,2,3]
for i in sorted(a):
    print(i)

结果:
2
3
5

猜你喜欢

转载自blog.csdn.net/weixin_42598585/article/details/85541231