python 列表,元组,字典,集合,字符串相互转换

Python015

python 列表,元组,字典,集合,字符串相互转换,第1张

li = [1, 2, 3]

t = tuple(li)

print(t, type(t))

del list #先清除list缓存

tu = (1, 2, 3)

li = list(tu)

print(li, type(li))

li = ['人', '生', '苦', '短']

str1 = ''.join(li)

print(str1, type(str1))

str2 = 'hello python'

li1 = str2.split(' ')

print(li1, type(li1))

list1 = ['name', 'age', 'sex']

list2 = ['张三', 18, '男']

dict = {}

for i in range(len(list1)):

dict[list1[i]] = list2[i]

print(dict, type(dict))

del dict#清除缓存

list1 = ['name', 'age', 'sex']

list2 = ['张三', 18, '男']

d = dict(zip(list1, list2))

print(d)

dict = {'name': '张三', 'age': 18, 'sex': '男'}

keys = list(dict.keys())

values = list(dict.values())

print(keys, type(keys))

print(values, type(values))

list3 = [['key1','value1'],['key2','value2'],['key3','value3']]

print(dict(list3))

list1 = [1, 3, 4, 3, 2, 1]

s1 = set(list1)

print(s1, type(s1))

list1 = [1, 3, 4, 3, 2, 1]

s1 = set(list1)

list2 = list(s1.intersection(s1))

print(list2, type(list2))

list = []

a = '人生苦短'

list.append(a)

print(list)

b = tuple(list)

print(b, type(b))

dict = {'name': 'xiaoming', 'age': 18}

tup = tuple(dict)

print(tup) # 只转换了key

tup2 = tuple(dict.values())

print(tup2)

dic1 = {'a': 1, 'b': 2}

str1 = str(dic1)

dic2 = eval("{'name':'xiaoming', 'age':18}")

print(dic2, type(dic2))

str1 = 'hello'

s1 = set(str1)

print(s1, type(s1))

dic1 = {'a': 1, 'b': 2, 'c': 3}

dic2 = {value: key for key, value in dic1.items()}

print(dic2)

列表、元组、集合、字典相互转换

一、列表元组转其他

1、列表转集合(去重)

list1 = [6, 7, 7, 8, 8, 9]

set(list1)

# {6, 7, 8, 9}

2、两个列表转字典

list1 = ['key1','key2','key3']

list2 = ['1','2','3']

dict(zip(list1,list2))

# {'key1': '1', 'key2': '2', 'key3': '3'}

3、嵌套列表转字典

list3 = [['key1','value1'],['key2','value2'],['key3','value3']]

dict(list3)

# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

4、列表、元组转字符串

list2 = ['a', 'a', 'b']

''.join(list2)

# 'aab'

tup1 = ('a', 'a', 'b')

''.join(tup1)

# 'aab'

二、字典转其他

1、 字典转换为字符串

dic1 = {'a':1,'b':2}

str(dic1)

# "{'a': 1, 'b': 2}"

2、字典key和value互转

dic2 = {'a': 1, 'b': 2, 'c': 3}

{value:key for key, value in a_dict.items()}

# {1: 'a', 2: 'b', 3: 'c'}

三、字符串转其他

1、字符串转列表

s = 'aabbcc'

list(s)

# ['a', 'a', 'b', 'b', 'c', 'c']

2、字符串转元组

tuple(s)

# ('a', 'a', 'b', 'b', 'c', 'c')

3、 字符串转集合

set(s)

# {'a', 'b', 'c'}

4、字符串转字典

dic2 = eval("{'name':'ljq', 'age':24}")

5、切分字符串

a = 'a b c'

a.split(' ')

# ['a', 'b', 'c']

1、说明

python使用tuple关键字来转换元组。

2、示例

a = "123456789"

z = tuple(a)

print(z)

3、执行结果

4、其它说明

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

tuple(seq)可以将列表转换为元组,上例就是如此使用。