python字符串/列表/字典互相转换
目录
字符串与列表
字符串与字典
列表与字典
字符串与列表
字符串转列表
1.整体转换
str1 =
'
hello world
'
print
(str1.split(
'
这里传任何字符串中没有的分割单位都可以,但是不能为空
'
))
#
输出:['helloworld']
2.分割
str2 =
"
hello world
"
list2
=
list(str2)
print
(list2)
#
输出:['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
str3 =
"
en oo nn
"
list3
=
str3.split()
#
list2 = str3.split(" ")
print
(list3)
#
输出:['en', 'oo', 'nn']
列表转字符串
1.拼接
list1 = [
'
hello
'
,
'
world
'
]
res
= list1[0] + list1[1
]
print
(res)
#
输出:helloworld
2.join
list2 = [
'
hello
'
,
'
world
'
]
#
引号中的内容为,连接各个字符串的字符
print
(
""
.join(list2))
print
(
"
"
.join(list2))
print
(
"
.
"
.join(list2))
#
输出:helloworld
#
输出:hello world
#
输出:hello.world
字符串与字典
字符串转字典
请查看这篇博文
字典转字符串
1.json
import
json
dict_1
= {
'
name
'
:
'
linux
'
,
'
age
'
:18
}
dict_string
=
json.dumps(dict_1)
print
(type(dict_string))
#
输出:
2.强制
dict_2 = {
'
name
'
:
'
linux
'
,
'
age
'
:18
}
dict_string
=
str(dict_2)
print
(type(dict_string))
#
输出:
列表与字典
列表转字典
两个列表
list1 = ['k1','k2','k3'] 、 list2 = [1,2,3] ,转换成字典{’k1‘:1,'k2':2,'k3':3}
list1 = [
'
k1
'
,
'
k2
'
,
'
k3
'
]
list2
= [1,2,3
]
print
(dict(zip(list1,list2)))
#
输出:{'k1': 1, 'k2': 2, 'k3': 3}
#zip() 函数用于将 可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。 zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换;如需展示成字典,需要手动dict()转换,如果元素个数不对应会报错。
嵌套列表
list2 = [[
'
key1
'
,
'
value1
'
],[
'
key2
'
,
'
value2
'
],[
'
key3
'
,
'
value3
'
]]
print
(dict(list2))
#
输出:{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
字典转列表
dict = {
'
name
'
:
'
Zara
'
,
'
age
'
: 7,
'
class
'
:
'
First
'
}
print
(list(dict))
#
输出:['name', 'age', 'class']

