python3-數據結構

 

列表(List)

1.列表中的每一個元素都是可變的,可以在列表中添加、刪除和修改元素。

2.列表中的元素是有序的,也就是說每一個元素都有一個位置(索引),可以通過位置(索引)查詢對應的值。

3.列表可以容納Python中的任何對象

all_in_list = [
 1,              #整數
 1.0,            #浮點數
 'a word',       #字符串
 print(1),       #函數
 True,           #布爾值
 [1,2],          #列表中套列表
 (1,2),          #元組
 {'key':'value'} #字典
]

列表的增刪改查

#添加
fruit = ['pineapple','pear']
fruit.insert(1,'grape')
print(fruit)
#輸出結果
['pineapple', 'grape', 'pear']

#刪除
fruit = ['pinapple','pear','grape']
fruit.remove('grape')
print(fruit)
#輸出結果
['pinapple', 'pear']

fruit = ['pinapple','pear','grape']
del fruit[0:2]
print(fruit)
#輸出結果
['grape']

#修改
fruit[0] = 'Grapefruit'

periodic_table = ['H','He','Li','Be','B','C','N','O','F','Ne']
print(periodic_table[0])
print(periodic_table[-2])
print(periodic_table[0:3])
print(periodic_table[-10:-7])
print(periodic_table[-10:]) 
print(periodic_table[:9])
#輸出結果
H
F
['H', 'He', 'Li']
['H', 'He', 'Li']
['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne']
['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F']

字典(Dictionary)

1.字典中的數據必須以鍵值對的形式出現。

2.邏輯上講,件事不能重複的,而只是可以重複的。

3.字典的鍵(key)是不可變的,也就是無法修改的;而值(value)是可變的,可修改的,可以是任何對象。

dic_code = {
    'int':123,
    'float':1.23,
    'str':'abc',
    'bool':True,
    'list':[123,'abc'],
    'dictionary':{'key':'value'},
    'function':print(1),
    'tuple':(123,'abc'),            #元組
    'int':456,            #相同鍵名,後者會覆蓋前者
}
print(dic_code)

#輸出結果
{
'int': 456, 
'float': 1.23, 
'str': 'abc', 
'bool': True, 
'list': [123, 'abc'], 
'dictionary': {'key': 'value'}, 
'function': None, 
'tuple': (123, 'abc')
}

 

#列表解析式
a = [i**2 for i in range(1,10)]
c = [j+1 for j in range(1,10)]
k = [n for n in range(1,10) if n % 2 ==0 and n != 2]
z = [letter.lower() for letter in 'ABCDEFGHIGKLMN']
print(a)
print(c)
print(k)
print(z)

#輸出結果
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
[4, 6, 8]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'k', 'l', 'm', 'n']

#字典解析式
d = {i:i+1 for i in range(4)}
e = {i:j for i,j in zip(range(1,6),'abcde')}
g = {i+1:j.upper() for i,j in zip(range(1,6),'abcde')}
print(d)
print(e)
print(g)

#輸出結果
{0: 1, 1: 2, 2: 3, 3: 4}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
{2: 'A', 3: 'B', 4: 'C', 5: 'D', 6: 'E'}

 

發佈了76 篇原創文章 · 獲贊 5 · 訪問量 9213
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章