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

Python016

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)

此处直接报错

Traceback (most recent call last):

File "<pyshell#27>", line 1, in <module>

print(" ".join(list1))

TypeError: sequence item 0: expected str instance, int found

解决方案:

print(" ".join('%s' %id for id in list1))

即遍历list的元素,把他转化成字符串。这样就能成功输出1 two three 4结果了。

原文链接: http://t.csdn.cn/AwUqX

完成这些数符转换,需要借助int(x)字符串转换工具,需要用到python编辑器,具体步骤如下:

1、打开任意python编辑器,这里以jupyternotebook为例

2、以一个字母表组成的字符串为例,将其转换成由每个字母组成的列表

3、以一个数字组成的字符串为例,将其转换成由每个数字组成的列表。

4、若字符串中存在符号,可据此分割并转化成列表。如图,字符串中存在逗号:

5、其它符号原理相同,如图中根据符号“/”进行分割。

6、同理,字符串中其它元素亦可用来作为分割条件,进而转化成列表。如图中的1,可据此作为分割: