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

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

服务器之家 - 脚本之家 - Python - python三种数据结构及13种创建方法总结

python三种数据结构及13种创建方法总结

2022-01-04 00:03数据分析与统计学之美 Python

拿Python来说,数据结构的概念也是超级重要,不同的数据结构,有着不同的函数,供我们调用,接下来,我们分别来介绍字符串、列表、字典的创建方法

Python常用的数据结构,有如下几种。但是我们用的最多的,还是字符串、列表、字典这3种。

python三种数据结构及13种创建方法总结

其实学习任何一门编程语言,最基础的就是学习它的数据结构。

 

字符串的3种创建方式

① 单引号(‘ '),创建字符串

a = 'I am a student'
print(a)

结果如下:

python三种数据结构及13种创建方法总结

② 双引号(“ ”),创建字符串

b = "I am a teacher"
print(b)

结果如下:

python三种数据结构及13种创建方法总结

③ 续3个单引号或者3个单引号,创建多行字符串

c = '''
I am a student
My name is黄伟
I am a teacher
My name is陈丽
'''
print(c)

结果如下:

python三种数据结构及13种创建方法总结

 

列表的5种创建方式

① 用[]创建列表

a = [1,2,3]
print(a)

结果如下:

python三种数据结构及13种创建方法总结

② 用list创建列表

b = list('abc')
print(b)

c = list((1,2,3))
print(c)

d = list({"aa":1,"bb":3}) #对于字典,生成的是key列表。
print(d)

结果如下:

python三种数据结构及13种创建方法总结

③ 用range创建整数列表

e = list(range(10))
print(e)

结果如下:

python三种数据结构及13种创建方法总结

④ 用列表推导式创建列表

f = [i for i in range(5)]
print(f)

结果如下:

python三种数据结构及13种创建方法总结

⑤ 用list和[]创建空列表

g = list()
print(g)
h = []
print(h)

结果如下:

python三种数据结构及13种创建方法总结

 

字典的5种创建方式

① 用{}创建字典

a = {'name':'陈丽','age':18,'job':'teacher'}
print(a)

b = {'name':'陈丽','age':18,'job':['teacher','wife']}
print(b)

结果如下:

python三种数据结构及13种创建方法总结

② 用dict创建字典

c = dict(name='张伟',age=19)
print(c)

d = dict([('name','李丽'),('age',18)])
print(d)

结果如下:

python三种数据结构及13种创建方法总结

③ 用zip函数创建字典

x = ['name','age','job']
y = ['陈丽','18','teacher']
e = dict(zip(x,y))
print(e)

结果如下:

python三种数据结构及13种创建方法总结

④ 用{},dict创建空字典

f = {}
print(f)
g = dict()
print(g)

结果如下:

python三种数据结构及13种创建方法总结

⑤ 用fromkeys创建'值为空'的字典

h =dict.fromkeys(['name','age','job'])
print(h)

结果如下:

python三种数据结构及13种创建方法总结

以上就是python三种数据结构及13种创建方法总结的详细内容,更多关于python数据结构及创建方法的资料请关注服务器之家其它相关文章!

原文链接:https://huang-tong-xue.blog.csdn.net/article/details/109278148

延伸 · 阅读

精彩推荐