脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 实现list,tuple,str和dict之间的相互转换

Python 实现list,tuple,str和dict之间的相互转换

2021-09-18 00:14Violet-Guo Python

这篇文章主要介绍了Python 实现list,tuple,str和dict之间的相互转换,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1、字典(dict)

?
1
dict = {‘name': ‘Zara', ‘age': 7, ‘class': ‘First'}

1.1 字典——字符串

返回:

?
1
print type(str(dict)), str(dict)

1.2 字典——元组

返回:(‘age', ‘name', ‘class')

?
1
print tuple(dict)

1.3 字典——元组

返回:(7, ‘Zara', ‘First')

?
1
print tuple(dict.values())

1.4 字典——列表

返回:[‘age', ‘name', ‘class']

?
1
print list(dict)

1.5 字典——列表

?
1
print dict.values

2、元组

?
1
tup=(1, 2, 3, 4, 5)

2.1 元组——字符串

返回:(1, 2, 3, 4, 5)

?
1
print tup.__str__()

2.2 元组——列表

返回:[1, 2, 3, 4, 5]

?
1
print list(tup)

2.3 元组不可以转为字典

3、列表

?
1
nums=[1, 3, 5, 7, 8, 13, 20];

3.1 列表——字符串

返回:[1, 3, 5, 7, 8, 13, 20]

?
1
print str(nums)

3.2 列表——元组

返回:(1, 3, 5, 7, 8, 13, 20)

?
1
print tuple(nums)

3.3 列表不可以转为字典

4、字符串

4.1 字符串——元组

返回:(1, 2, 3)

?
1
print tuple(eval("(1,2,3)"))

4.2 字符串——列表

返回:[1, 2, 3]

?
1
print list(eval("(1,2,3)"))

4.3 字符串——字典

返回:

?
1
print type(eval("{'name':'ljq', 'age':24}"))

补充:python入门之路:一个小错误,str变tuple

笔者在编程的时候发现,原先定义的str字符串在传递和引用的时候会莫名其妙改变类型,变成tuple。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import random
class get_Veri(object):
  def random_color(self):
    random_color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))
    return random_color
 
  def random_num(self):
    random_num = str(random.randint(0, 9))
    return random_num
 
  def random_lowerchr(self):
    random_lowerchar=chr(random.randint(97, 122))
    return random_lowerchar
 
  def random_upperchr(self):
    random_upperchr = chr(random.randint(65, 90))
    return random_upperchr
 
  def random_char(self):
    random_char = random.choice([get_Veri.random_num(self), get_Veri.random_upperchr(self), get_Veri.random_lowerchr(self)])
    print(random_char)
    print(type(random_char))
    return random_char

这里random_char函数输出一个随机字符串,可以看到type类型为:

?
1
<class 'str'>

在另一个文件中进行引用:

?
1
2
3
4
5
6
from random_data.py import get_Veri
 
get_veri=get_Veri()
random_char = get_veri.random_char(),
print(random_char)
print(type(random_char))

发现random_char的type类型已经发生改变:

?
1
<class 'tuple'>

只是一个简单的赋值,为什么会发生改变?

原因是在赋值的时候多加了一个逗号。

这个逗号让编译器执行的时候理解为("str",)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/violet_echo_0908/article/details/52486689

延伸 · 阅读

精彩推荐