python列表转化字典_python字符串/列表/字典互相转换

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

importjson

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']

字符串与数值

字符串转数值

int(str) 函数将 符合整数的规范的字符串 转换成 int 型。

num2 = "123";

num2=int(num1);print("num2: %d" % num2);

float(str) 函数将 符合 浮点型 的规范的字符串 转换成 float 型。

num1 = "123.12";

num2=float(num1);print("num2: %f" % num2);

数值转字符串

str(num) 将 整数,浮点型转换成 字符串。

num = 123;

mystr=str(num);print ("%s" % mystr);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值