1. 程式人生 > >Python的字串,列表,字典,元組,集合之間的型別互轉

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