在这篇文章中,我们将为您详细介绍用于管理依赖项的Python数据结构的内容,并且讨论关于python依赖管理工具的相关问题。此外,我们还会涉及一些关于(二)python数据结构(字典及练习)、6、Py
在这篇文章中,我们将为您详细介绍用于管理依赖项的 Python 数据结构的内容,并且讨论关于python 依赖管理工具的相关问题。此外,我们还会涉及一些关于(二) python 数据结构(字典及练习)、6、Python —— 数据结构、python 2.7 数据结构: 基础面试总结、Python 3 -- 数据结构(list, dict, set,tuple )的知识,以帮助您更全面地了解这个主题。
本文目录一览:- 用于管理依赖项的 Python 数据结构(python 依赖管理工具)
- (二) python 数据结构(字典及练习)
- 6、Python —— 数据结构
- python 2.7 数据结构: 基础面试总结
- Python 3 -- 数据结构(list, dict, set,tuple )
用于管理依赖项的 Python 数据结构(python 依赖管理工具)
如何解决用于管理依赖项的 Python 数据结构
我正在通过创建一个脚本来学习 python3,该脚本的目的是在服务器上部署一些工件。 要求是工件可以依赖于一个或多个工件,如果尚未安装其依赖项,则不应安装。
此工件的安装顺序及其依赖项(如果有)很重要,也应该以多线程/多处理方式完成。
目前我的 dependencies
属性是一个列表,但我正在考虑使用 Queue
或 Python 中的链表实现。
我已经定义了一个 Artifact 类,但我不确定哪个是适合依赖项集合的数据结构。
任何想法将不胜感激。
class Artifact:
name: str = None
download_path: str = None
zip_file_path: str = None
tar_file_path: str = None
control_file_path: str = None
download_urls: [str] = []
btt_files: [str] = []
checksum_passed: bool = False
dependencies: [] = None
def __init__(self,name: str):
self.name = name
(二) python 数据结构(字典及练习)
1、字典:是python里面的数据结构,字典的对象value是可变的,但是字典的键值key是不可变的,一个字典可以使用不同类型的键值(元组);不能使用列表list,因为列表是可变的, 因为字典是hash 表显示是无序的;
可用来存储一个人年龄 身高 性别等;
当然字符串也可以存储的,但是如果有的姓名不是3个,那就取得不全的;
info = ''tom 180 man''
info[0:3]
''tom''
当然也可以存储元组里,但是元组一旦定义完之后,里面的元素就不能更改,那么如果增加联系人 等信息就无法添加了; read only
当然也可以存储到列表里, 但是将来取数据也比较麻烦,通过下标来取,不知道索引就无法取了;
如下:先创建一个list1 list2 list3 并用zip函数把他们连接到一起;然后把这些信息放到字典里,然后取就很方便了;
In [298]: list1 = [''name'', ''age'']
In [300]: list2 = [''tom'',''20'']
In [301]: list3 = [''mike'',''25'']
In [302]: list2
Out[302]: [''tom'', ''20'']
In [303]: zip(list1, list2)
Out[303]: [(''name'', ''tom''), (''age'', ''20'')]
In [304]: list1
Out[304]: [''name'', ''age'']
In [305]: list2
Out[305]: [''tom'', ''20'']
In [306]: zip(list1, list3)
Out[306]: [(''name'', ''mike''), (''age'', ''25'')]
注释:zip函数会把两个列表合并,组成一个大的列表;
注释:列表 [ ] 元组 ( ) 字典 { } 字符串 '' ''
字典的方法:
keys() 返回当前字典中所有的keys 值; dic.keys()
values() 返回当前字典中所有的value值; dic.value()
items()
创建字典; dic { }
dic = {''a'':1, 1:123} a 表示key 键值 1 表是 value 中间用冒号 : 隔开;
In [307]: dic = {}
In [308]: type(dic)
Out[308]: dict
In [309]: dic = {''a'':1, 1:123} #创建两对数据; key - value 对应;
In [310]: dic
Out[310]: {1: 123, ''a'': 1}
2、那么用元组()作为key值来创建字典;如下;因为元组()是不可变的,可以用来当做key 键值; dc = {(''a'',''b''):''hello''}
In [313]: dc = {(''a'',''b''):''hello''}
In [314]: type(dc)
Out[314]: dict
In [315]: dc
Out[315]: {(''a'', ''b''): ''hello''}
3、那么用list[]来作为key 值创建字典,不可以的,因为list是可变的;
In [317]: dc1 = {[1]:1}
------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-317-c906c08b610a> in <module>()
----> 1 dc1 = {[1]:1}
TypeError: unhashable type: ''list''
注释:如上图例,所有list[ ] 不能当做字典的键值 key 来使用;
len(dic) 也可以看字典的长度;
4、字典的参数如下;
dic.key() 返回所有key值组成一个列表list并显示;
In [319]: dic.keys()
Out[319]: [''a'', 1, (''a'', ''b'')]
dic.values() 返回所有value值组成一个列表list并显示;
In [320]: dic.values()
Out[320]: [1, 123, ''hello'']
3、字典的相关参数: 通过 help(dic.get) 来查看对应的帮助;
n [22]: dic.
dic.clear() 清空字典内容,只是清空,空字典还在 dic.get(key值) 输出 value
dic.iteritems dic.keys()返回当前字典中所有的keys
dic.setdefault dic.viewitems dic.copy() 复制一个新的字典 dic1 = dic.copy()
dic.has_key(key值) 判断key值是否在dic中,在则true,不在则flase
dic.iterkeys dic.pop(key) 删除这个key对应的value,并显示在屏幕上
dic.update(dic1) 里面跟一个列表,用来把两个字典合并成一个字典 dic.viewkeys
dic.formkeys(''abc'', 1) 序列 值 可以用来创建字典, 然后显示序列,值如果不写则为 NONE, 使用value 值时一样的字典; dic.items 把字典转换成列表list,里层是元组tuple,方便用切片或者索引;
dic.itervalues dic.popitem dic.values() 返回当前字典中所有的values
dic.viewvalues
dic.clear dic.get(key值) 输出 value dic.iteritems dic.keys dic.setdefault dic.viewitems
dic.copy dic.has_key() dic.iterkeys dic.pop dic.update dic.viewkeys
dic.fromkeys dic.items dic.itervalues dic.popitem dic.values dic.viewvalues
dic.get 通过 help(dic.get)
get(...) k 表示 key 值 D 表示 dic 字典 ;如果key在dic字典里,返回值value ,否则返回none 空;
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
In [26]: dic
Out[26]: {1: 123, ''a'': 1, (''a'', ''b''): ''hello''}
In [27]: dic.get(1)
Out[27]: 123
In [28]: dic.get(''a'')
Out[28]: 1
In [29]: dic.get(''p'')
如上,如果返回值不存在,则是none,如果后面添加,则返回后面的值;
In [40]: dic.get(''b'',''linux'')
Out[40]: ''linux''
注释:字典里的key 是唯一的,不能冲突;不能改变,当往里面添加时,则会改变 value 值;
In [32]: dic[''a'']
Out[32]: 1
In [33]: dic[''a''] = 3
In [34]: dic
Out[34]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
注释: 查看字典某个key - value: dic[''a''] dic.get(''a'')
4、判断一个 key 在不在字典里; 在则 返回 ture 不在则返回flase; 方法一:
In [52]: dic
Out[52]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
In [53]: ''b'' in dic
Out[53]: False
In [54]: ''a'' in dic
Out[54]: True
In [55]: 1 in dic
Out[55]: True
判断一个key 在不在字典里, 在则 true 不在则flase;
In [57]: dic
Out[57]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
In [58]: dic.has_key(''a'')
Out[58]: True
In [59]: dic.has_key(''b'')
Out[59]: False
In [60]: dic.has_key(1)
Out[60]: True
注释:判断是否在dic 字典中 ''key'' in dic ===== dic.has_key(key)
5、dic.items() 把字典内容转换成列表 list,最里层是元组 tuple 的形式;这样就可以通过索引和切片的方式来访问里面的值了;
In [70]: dic.items()
Out[70]: [(''a'', 3), (1, 123), ((''a'', ''b''), ''hello'')]
In [71]: dic
Out[71]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
6、dic.copy() 用于复制,然后产生一个新的字典; dic1 = dic.copy()
In [71]: dic
Out[71]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
In [72]: dic1 = dic.copy()
In [73]: dic1
Out[73]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
7、dic.clear() 清空字典内容,只是清空而已,空字典还在; dic.clear()
In [73]: dic1
Out[73]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
In [74]: dic1.clear()
In [75]: dic1
Out[75]: {}
8、dic.pop(key) 里面加key值,会删除这个key对应的value,并返回至屏幕上;
In [78]: dic1
Out[78]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
In [79]: dic1.pop(1)
Out[79]: 123
In [80]: dic1
Out[80]: {''a'': 3, (''a'', ''b''): ''hello''}
In [81]: dic1.pop(2)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-81-e47c27be2010> in <module>()
----> 1 dic1.pop(2)
KeyError: 2
In [82]: dic1.pop(2,''abc'')
Out[82]: ''abc''
9、dic.update(dic1) 里面跟一个列表,用来把两个字典合并成一个字典;
In [84]: dic
Out[84]: {1: 123, ''a'': 3, (''a'', ''b''): ''hello''}
In [85]: dic1 = {1:1, 2:2}
In [86]: dic.update(dic1)
In [87]: dic
Out[87]: {1: 1, 2: 2, ''a'': 3, (''a'', ''b''): ''hello''}
注释:如上dic1是一个字典;
创建字典:
10、dic.formkeys(''abc'', 1) 序列 值 可以用来创建字典, 然后显示序列,值如果不写则为 NONE, 使用value 值时一样的字典;
In [99]: dic.fromkeys(''abc'') #只写了序列 key, 不写 值;
Out[99]: {''a'': None, ''b'': None, ''c'': None}
In [101]: dic.fromkeys(''abc'',100) #写了序列key, 值会都是一样的;
Out[101]: {''a'': 100, ''b'': 100, ''c'': 100}
用range(100) 也可以;
In [102]: dic.fromkeys(range(10),100)
Out[102]:
{0: 100,
1: 100,
2: 100,
3: 100,
4: 100,
5: 100,
6: 100,
7: 100,
8: 100,
9: 100}
创建字典的方法: dic ( [( )] )
In [96]: dict([(''name'', ''tom''), (''age'', ''20'')]) #可以用这种方法;
Out[96]: {''age'': ''20'', ''name'': ''tom''}
In [97]: dict(a=10, b=10) #可以用这种方法;
Out[97]: {''a'': 10, ''b'': 10}
方法一:
In [119]: dict(x=10,y=10)
Out[119]: {''x'': 10, ''y'': 10}
方法二:
In [120]: dic = {}
In [121]: dict(x=10,y=10)
Out[121]: {''x'': 10, ''y'': 10}
方法四:
In [122]: dic = {''a'':1, 1:123}
方法三: 可以使可迭代的对象;
In [123]: dict([(''a'',10),(''b'',20)])
Out[123]: {''a'': 10, ''b'': 20}
方法五:
In [124]: dic.fromkeys(''abc'',100)
Out[124]: {''a'': 100, ''b'': 100, ''c'': 100}
访问字典:
通过打印key 输入 value 来访问; dic[key]
In [126]: dic[''a'']
Out[126]: 1
通过dic.items() 来返回key value, 打印成 列表的形式; dic.items()
In [127]: dic1.items()
Out[127]: [(1, 1), (2, 2)]
3、也可以通过for循环的方式来访问:
for k in dic: for k in dic:
print k print k, dic[k]
In [129]: for k in dic: #只显示key值;
...: print k
...:
a
1
In [130]: for k in dic: #显示 key 和 value 值对应;
...: print k, dic[k]
...:
a 1
1 123
当然也可以用如下方法: for k in dic: print "%s, %s" % (k, dic[k])
In [137]: dic
Out[137]: {1: 123, ''a'': 1}
In [138]: for k in dic:
...: print "%s, %s" % (k, dic[k])
...:
a, 1
1, 123
注释:di = {1:1,3:3,2:2,4:4,5:5}
In [145]: for k, v in di.items():print k,v
1 1
2 2
3 3
4 4
5 5
6、字典练习, 读取键盘的文件:
raw_input 接收的字符串,无论输入什么,都会是字符串;
input 接受的是表达式,可以输入数值,也可以输入字符串(不过需要加单或双引号)
[root@localhost_002 python]# cat 2.py
#!/usr/bin/python
info = {}
name = raw_input("Please input name: ")
age = raw_input("Please input age: ")
gender = raw_input(''Please input (M/F): '')
info[''name''] = name
info[''age''] = age
info[''gender''] = gender
print info
#print info.items() 这样则会打印成列表的形式,方便索引和切片;
注释:如果把最后一行修改成 print info.items() 则会打印出一个列表,方便索引和切片;则打印成如下:
[(''gender'', ''M''), (''age'', ''24''), (''name'', ''yuan'')] #列表里面包括了元组tuple 来组成;
运行: python 2.py
[root@localhost_002 python]# python 2.py
Please input name: yuan
Please input age: 24
Please input (M/F): M
{''gender'': ''M'', ''age'': ''24'', ''name'': ''yuan''}
如果用列表的方式打印,就可以用传参的方式来接受key value; 如下:
[(''gender'', ''M''), (''age'', ''24''), (''name'', ''yuan'')]
a, b = (''age'', ''24'') 则 a 等于 age , b 等于 24;
[root@localhost_002 python]# python 2.py
Please input name: yuan
Please input age: 24
Please input (M/F): M
[(''gender'', ''M''), (''age'', ''24''), (''name'', ''yuan'')]
[root@localhost_002 python]# ipython
In [1]: a, b = (''age'', ''24'')
In [2]: a
Out[2]: ''age''
In [3]: b
Out[3]: ''24''
In [4]: c,d = (''name'', ''yuan'')
In [5]: c
Out[5]: ''name''
In [6]: d
Out[6]: ''yuan''
10:当然是序列(列表),就可以使用for 循环来遍历,读取每个元素;如下: 一般print 缩进四个空格即可;
[root@localhost_002 python]# cat 3.py
#!/usr/bin/python
info = {}
name = raw_input("Please input name: ")
age = raw_input("Please input age: ")
gender = raw_input(''Please input (M/F): '')
info[''name''] = name
info[''age''] = age
info[''gender''] = gender
for i in info.items():
print i
print "end"
运行:
[root@localhost_002 python]# python 3.py
Please input name: yuan
Please input age: 24
Please input (M/F): M
(''gender'', ''M'')
(''age'', ''24'')
(''name'', ''yuan'')
end
注释:只有序列才可以使用 索引 切片 for 循环等;
也可以传递两个参数 k v 来接收这个值: for k, v in info.items(): print k,v
[root@localhost_002 python]# cat 3.py
#!/usr/bin/python
info = {}
name = raw_input("Please input name: ")
age = raw_input("Please input age: ")
gender = raw_input(''Please input (M/F): '')
info[''name''] = name
info[''age''] = age
info[''gender''] = gender
for k,v in info.items():
print k,v
print "end"
运行:
[root@localhost_002 python]# python 3.py
Please input name: yuan
Please input age: 24
Please input (M/F): M
gender M
age 24
name yuan
end
当然也可以美化一下,在每一个字符串后面加上: 可以使用拼接符 + : for k,v in info.items(): print k+":",v
[root@localhost_002 python]# cat 5.py
#!/usr/bin/python
info = {}
name = raw_input("Please input name: ")
age = raw_input("Please input age: ")
gender = raw_input("Please input gentder: ")
info[''name''] = name
info[''age''] = age
info[''gender''] = gender
for k,v in info.items():
print k+":",v
# print "%s: %s" % (k, v) 这种方法也可以,这种方法用的更多一些;
print "end"
[root@localhost_002 python]# python 5.py
Please input name: yuan
Please input age: 24
Please input gentder: M
gender: M
age: 24
name: yuan
end
注释#: for k,v in info.items(): print k+":",v 与 for k,v in info.items(): print "%s: %s" % (k,v) 相同:
print "%s: %s" % (k, v) 这种格式化输出的方法用的更多一些;
如果只想求一个元素的话,则就 for k,v in ino,items(): print "%s" %k
6、Python —— 数据结构
1、列表(List)
# encoding: utf-8
#-----------------------------------------------------------------------------------------
# 1、list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。
# 2、列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。
# 3、一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。
# 4、我们说列表是可变的数据类型,即这种类型是可以被改变的。
#-----------------------------------------------------------------------------------------
# 对列表shopList进行赋值
shopList = [''apple'', ''orange'', ''banana'', ''mango'']
# 列表长度
print len(shopList)
# 4
# 遍历列表
for item in shopList:
print item
# 添加元素
shopList.append(''watermelon'')
print shopList
# [''apple'', ''orange'', ''banana'', ''mango'', ''watermelon'']
# 对列表进行排序
shopList.sort()
print shopList
# [''apple'', ''banana'', ''mango'', ''orange'', ''watermelon'']
# 获取列表中某个元素
myItem = shopList[1]
print myItem
# banana
# 删除某个元素
del shopList[0]
print shopList
# [''banana'', ''mango'', ''orange'', ''watermelon'']
2、元组(tuple)
# encoding: utf-8
#-----------------------------------------------------------------------------------------
# 1、元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。
# 2、元组通过圆括号中用逗号分割的项目定义。
# 3、元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。
#-----------------------------------------------------------------------------------------
# 元组赋值
pet = (''money'', ''cat'', ''dog'')
# 元组长度
print len(pet)
# 3
# 打印元组
print pet
# (''money'', ''cat'', ''dog'')
print pet[2]
# dog
# 元组赋值
new_pet = (''duck'', ''mouse'', pet)
print len(new_pet)
# 3
print new_pet
# (''duck'', ''mouse'', (''money'', ''cat'', ''dog''))
print new_pet[1]
# mouse
print new_pet[2]
# (''money'', ''cat'', ''dog'')
print new_pet[2][1]
# cat
#-----------------------------------------------------------------------------------------
# 1、元组最通常的用法是用在打印语句中
#-----------------------------------------------------------------------------------------
age = 22
name = ''cobish''
# 输出字符串
print ''my name is %s'' %name
# my name is cobish
# 输出字符串和整数
print ''%s is %d years old'' %(name, age)
# cobish is 22 years old
# 错误写法
print ''%s is %d years old'', name, age
# %s is %d years old cobish 22
3、字典
# encoding: utf-8
#-----------------------------------------------------------------------------------------
# 1、字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿
# 2、键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }
# 3、字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
#-----------------------------------------------------------------------------------------
# 字典赋值
email = {
''cobish'' : ''cobish@qq.com'',
''wabish'' : ''wabish@qq.com'',
''nebish'' : ''nebish@qq.com''
}
# 字典长度
print len(email)
# 3
# 打印字典
print email
# 通过''键''获取''值''
print "cobish''s email is %s" %email[''cobish'']
# cobish''s email is cobish@qq.com
# 增加一个键值对
email[''tabish''] = ''tabish@qq.com''
print email
# 删除一个键值对
del email[''wabish'']
print email
# 遍历字典
for name, address in email.items():
print "%s''s email is %s" %(name, address)
if ''nebish'' in email:
print "nebish''s email is %s" %email[''nebish'']
# nebish''s email is nebish@qq.com
4、序列
# encoding: utf-8
#-----------------------------------------------------------------------------------------
# 1、列表、元组和字符串都是序列。
# 2、序列的两个主要特点是索引操作符和切片操作符。
# 3、索引操作符让我们可以从序列中抓取一个特定项目。(主要用在列表之类)
# 4、切片操作符让我们能够获取序列的一个切片,即一部分序列。(主要用在字符串等)
#-----------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------
# 1、列表索引
# 2、索引可以是正数和负数
# 3、正数从序列头开始计算,复数从序列尾开始计算
#-----------------------------------------------------------------------------------------
fruitList = [''apple'', ''banana'', ''orange'', ''watermelon'']
print ''fruit 0 is'', fruitList[0] # apple
print ''fruit 1 is'', fruitList[1] # banana
print ''fruit 2 is'', fruitList[2] # orange
print ''fruit 3 is'', fruitList[3] # watermelon
# print ''fruit 4 is'', fruitList[4] 越界,访问错误
print ''fruit -1 is'', fruitList[-1] # watermelon
print ''fruit -2 is'', fruitList[-2] # orange
print ''fruit -3 is'', fruitList[-3] # banana
print ''fruit -4 is'', fruitList[-4] # apple
# print ''fruit -5 is'', fruitList[-5] 越界,访问错误
#-----------------------------------------------------------------------------------------
# 1、列表切片
# 2、切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。
# 3、注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。
# 4、切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。
#-----------------------------------------------------------------------------------------
print ''fruit 1 to 3 is'', fruitList[1:3] # [''banana'', ''orange'']
print ''fruit 2 to end is'', fruitList[2:] # [''orange'', ''watermelon'']
print ''fruit 1 to -1 is'', fruitList[1:-1] # [''banana'', ''orange'']
print ''fruit start to end'', fruitList[:] # [''apple'', ''banana'', ''orange'', ''watermelon'']
#-----------------------------------------------------------------------------------------
# 1、字符串切片
#-----------------------------------------------------------------------------------------
str = ''cobish''
print ''str 1 to 3 is'', str[1:3] # ob
print ''str 2 to end is'', str[2:] # bish
print ''str 1 to -1 is'', str[1:-1] # obis
print ''str start to end is'', str[:] # cobish
5、更多字符串方法
# encoding: utf-8
str = ''cobish''
# 以某某字符串开始
if str.startswith(''cob''):
print ''yes, it starts with "cob"''
# 某某字符串是否在里面
if ''b'' in str:
print ''yes, it contains the string "b"''
# 是否包含某某字符串
if str.find(''bis'') != -1:
print ''yes, it contains the string "bis"''
# str类有以一个作为分隔符的字符串join序列的项目的整洁的方法
delimiter = ''_*_''
mylist = [''Brazil'', ''Russia'', ''India'', ''China'']
print delimiter.join(mylist)
# Brazil_*_Russia_*_India_*_China
python 2.7 数据结构: 基础面试总结
python中基础的数据类型包括:
1 Number(数字)
2 String(字符串)
3 List(列表)
4 Tuple(元组)
5 set(集合)
6 Pictionary(字典)
按照可变数据和不可变数据来区分:
不可变数据(3个):Number(数字),String(字符串),Tuple(元组)
可变数据(3个):List(列表),Dictonary(字典),set(集合)
创建方式:
创建列表: listT=[1,2,3,4,5]
创建元组:tup2=(1,2,3,4,5)
创建字典:dict2={"abc":123,"def":789}
创建集合:student={''Tom'',''Jim'',''Mary''}
列表:列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)【插入数据可重复,数据不唯一】
listT=[1,"2",(3,4,5,6),[7,8,9],{"10":11},{12,13,14}] #列表可以存储数据类型:数字,字符,元组,列表,字典,set
print listT #得:[1, ''2'', (3, 4, 5, 6), [7, 8, 9], {''10'': 11}, set([12, 13, 14])]
元组:元组(tuple)与列表类似,元组不能二次赋值。【元组本身是只读对象,如果元组中的对象是可变类型数据,可变类型数据依然可以修改】
tuple=(1,"2",(3,4,5,6),[7,8,9],{"10":11},{12,13,14}) #元组可以存储数据类型:数字,字符,元组,列表,字典,set
print tuple
print tuple[0]
print tuple[3]
tuple[3][0]=77
print tuple[3]
一下为输出测试结果:
#(1, ''2'', (3, 4, 5, 6), [7, 8, 9], {''10'': 11}, set([12, 13, 14]))
# 1
#[7, 8, 9]
#[77, 8, 9]
字典:列表是有序的对象集合,字典是无序的对象集合【键必须是唯一的,但值则不必;值可以取任何数据类型,但键必须是不可变的】
dict2={1:1,"2":"2",(3):(3)}
print dict2 #得 {3: 3, 1: 1, ''2'': ''2''} 元组类型发生了改变
dict2={1:1,"2":"2",(3,2):(3,2)}
print dict2 #{1: 1, (3, 2): (3, 2), ''2'': ''2''} 元组未发生改变
dict2={1:1,"2":"2",(3,2):(3,2),4:[5],"5":{"66":"66"},(3):{"77","88"}} #键必须是不可变的,值可以是任何类型:依次为数字,字符,元组,列表,字典,set集合
print dict2 #得 {1: 1, (3, 2): (3, 2), 3: set([''77'', ''88'']), 4: [5], ''2'': ''2'', ''5'': {''66'': ''66''}}
集合:set是一个无序的不重复元素序列
set={1,"2",(3,2)}
print set # 得:set([1, (3, 2), ''2'']) ;看到数据结构后着实让人发现原来set集合内部结构也是一个列表。这就不难理解为啥可以用set给list列表去重
set={1,"2",(3,2)} #集合只能存放不可变类型,可变类型放入后会报错
print set
list=[4,5,6]
dict2={"9":"10"}
set={6,7,8}
#set.add(list) #TypeError: unhashable type: ''list''
#set.add(dict2) #TypeError: unhashable type: ''dict''
#set.add(set) #TypeError: unhashable type: ''set''
面试常问问题:
1 list列表可以存储的类型结构:数字,字符串,元组,列表,字典,set
2 tuple元组可以存储数据类型:数字,字符,元组,列表,字典,set
3 dict字典可以存储数据类型:分别说:键(不可变),值(数字,字符,元组,列表,字典,set集合)
4 set集合可以存储数据类型:不可变类型(数字,字符,元组)
未完待续》》
补充数据类型转换
原文出处:https://www.cnblogs.com/renguiyouzhi/p/10476060.html
Python 3 -- 数据结构(list, dict, set,tuple )
看了《Head First Python》后,觉得写的很不错,适合新手。此处为读书笔记,方便日后查看。
Python 提供了4中数据结构:list,dict,set,tuple. 每种结构都有自己的特征和用处。
1. List -- 有序的可变对象集合
- List 的定义
prices = [] # 定义空列表
temps = [32.0, 212.0, 0.0, 81.6, 100.0, 45.3] # 存储浮点型
words = [''hello'',''word''] # 存储字符串
car_details = [''Toyota'', ''RAV2'', 2.2, 60808] # 列表中可以存储混合类型数据
everyting = [prices, temps, words, car_details] # 列表里放置列表
- List 常用操作,以下操作直接影响list的值。
fruit=[''banana'',''orange'',''strawberry'']
# 打印列表中全部元素
for v in fruit:
print(v)
# 判断列表中是否存在某个元素,若不存在加入到列表中。
if ''apple'' not in fruit:
fruit.append(''apple'')
print(fruit)
# 打印列表长度
print(len(fruit))
# 从列表总添加元素
fruit.append(''piers'')
print(fruit)
# 从列表中删除某个对象值
numsRem=[1,2,3,4]
numsRem.remove(3)
print(''Remove result is ''+str(numsRem))
# nums -> [1,2,4]
# 从列表中删除某个位置(索引值)的对象
numsPop=[1,2,3,4]
numsPop.pop() #->4
print(''Pop result is ''+str(numsPop))
#nums->[1,2,3]
# 加入一个其他列表
nums1=[1,2]
nums2=[3,4]
nums1.extend(nums2)
print(nums1) # [1,2,3,4]
# 从列表的某个位置插入指定元素值
numsIns=[2,3,4]
numsIns.insert(0,1)
print(numsIns) #[1,2,3,4]
- List 和 String 的相互转换
given_message = "It''s a known issue."
print("given message original is \''" + given_message +" \''")
# convert string to list
mes_list = list(given_message)
print("List given message is " + str(mes_list))
# convert list to string
given_message_after = ''''.join(mes_list)
print("After converted to string is \''" + given_message_after + " \''")
- 从list取特定字段, 以下操作除了rename以外,其他操作都是生成一个副本,不会改变原list的值。
list1=[1,2,3,4,5,6]
print ("list1 is "+ str(list1))
# It will give a alise for list1, but not copy of it. So if one of them is changed, the other one will be changed also.
list1_rename = list1
print ("list1_rename is " + str(list1_rename))
list1_rename[0]=9
print("After list1_rename[0]=9, list1_rename is " + str(list1_rename))
print("After list1_rename[0]=9, list1 is " + str(list1))
# Copy a list, so if one of it has been changed, the other will not be changed.
list1_copy = list1.copy()
print("list1_copy is " + str(list1_copy))
list1_copy[0]= 8
print("After list1_copy[0]= 8, list1_copy is " + str(list1_copy))
print("After list1_copy[0]= 8, list1 is " + str(list1))
# Get value by index
print("list 1 is " + str(list1))
print("first value is " + str(list1[0]))
print("last value is " + str(list1[-1])) #navigate index get the value from the end.
print("Value for every 3 index is " + str(list1[0:5:3]))
print("Value from index 3 is " + str(list1[3:]))
print("Value until index 4 is " + str(list1[:4]))
print("value all for every 2 index is " + str(list1[::2]))
# get back ward value
print("Backward value for list1 is " + str(list1[::-1]))
print("Backward value for target range is " + str(list1[4:1:-1]))
2. Dict:
Dict -- 无序的键/值对集合
- Dict的定义
dict1 = {}
dict_person = {''Name'':''Steven'',''Gender'':''Male'',''Occupation'':''Researcher'',''Home Planet'':''Betelgeuse Seven''}
print("dict1 is "+ str(dict1))
print("dict_person" + str(dict_person))
- Dict的常用操作
dict_person = {''Name'':''Steven'',''Gender'':''Male'',''Occupation'':''Researcher'',''Home Planet'':''Betelgeuse Seven''}
# Get value by index
print("dict_person''s name is " + str(dict_person[''Name'']))
# Add an key and value
dict_person[''Age'']= 33
print("After dict_person[''Age'']= 33, dict_person''s new:value is " + str(dict_person))
# 遍历dict中的所有key
for k in dict_person:
print(k)
# 遍历dict中的所有value
for k in dict_person:
print(dict_person[k])
# 遍历dict中的所有值
for k in dict_person:
print(k +":" + str(dict_person[k]) + "\t")
# 遍历dict中的所有值
for k,v in dict_person.items():
print(k +":" + str(dict_person[k]) + "\t")
# 遍历dict中的所有值(按顺序显示)
for k,v in sorted(dict_person.items()):
print(k +":" + str(dict_person[k]) + "\t")
# 用字典记录频度, 输出给定字符串中元音出现的次数
count_for_string = ''Hello, hello, how are you''
vowels = [''a'',''e'',''i'',''o'',''u'']
found ={}
for k in count_for_string:
if k in vowels:
found.setdefault(k,0)
found[k] +=1
- 字典的嵌套(也就是表)
from pprint import pprint
person={}
person[''Mother'']={''Name'':''Luky'',''Age'':''28'',''Sex'':''Female''}
person[''Father'']={''Name'':''Alex'',''Age'':''31'',''Sex'':''Male''}
person[''Son1'']={''Name'':''Ethan'',''Age'':''3'',''Sex'':''Male''}
person[''Son2'']={''Name'':''Ringo'',''Age'':''1'',''Sex'':''Female''}
# 显示整张嵌套列表
for k,v in sorted(person.items()):
print(str(k) + '':'' + str(v))
for k,v in sorted(person.items()):
pprint(str(k) + '':'' + str(v))
# 显示嵌套列表的某个值
print(person[''Mother''][''Age''])
3. Set
Set -- 无序的唯一对象集合(不允许有重复,可以用于去重)
- Set 的定义:
# 定义空字符串
set_a=()
print(set_a)
# 从列表创建集合
set_volew=set(''aaioeuu'')
print(set_volew)
- Set的常用:
# 并集
volews=set(''aeiou'')
world="Hello,Apple"
union_letters=volews.union(set(world))
print(union_letters)
# 差集(A-B),这里是volews letter - world letter
diff_letters=volews.difference(set(world))
print(diff_letters)
# 交集
inst_letters=volews.intersection(set(world))
print(inst_letters)
4. Tuple
Tuple-- 有序的不可变对象集合,其实也是一个一旦创建(并填充数据)就不能改变的列表,这样性能更好。
- 元组的定义
# 元组的定义
vowels_tuple=(''a'',''e'',''i'',''o'',''u'')
print(vowels_tuple)
- 元组常用操作
# 给元组更新值会报错,因为元组值是不能变的。
# 如vowels_tuple[2]=''A'' 会报TypeError: ''tuple'' object does not support item assignment
# 显示某个元素
print(vowels_tuple[0])
# 只有一个对象的元组赋值一定要加'',''号,否则不会被视为元组.
tuple=(''python'')
print(type(tuple)) # <class ''str''>
tuple2=(''python'',)
print(type(tuple2)) # <class ''tuple''>
欢迎转载,如需转载请注明出处。
今天关于用于管理依赖项的 Python 数据结构和python 依赖管理工具的讲解已经结束,谢谢您的阅读,如果想了解更多关于(二) python 数据结构(字典及练习)、6、Python —— 数据结构、python 2.7 数据结构: 基础面试总结、Python 3 -- 数据结构(list, dict, set,tuple )的相关知识,请在本站搜索。
本文标签: