网络编程
位置:首页>> 网络编程>> Python编程>> python三种数据结构及13种创建方法总结

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

作者:数据分析与统计学之美  发布时间:2021-03-23 04:46:52 

标签: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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com