Chapter9 Dictionary
1. list and dictionary
(1)順序
List: 有序-linear collection of values that stay in order. (一盒薯片)
Dictionary: 無(wú)序-’bag’ of values, each with its own label. (key + value)
lst=list()
lst.append(21)
lst.append(183)
print(lst)
[21, 183]
ddd=dict()
ddd['age']=21
ddd['course']=183
print(ddd)
{‘a(chǎn)ge’: 21, ‘course’: 183}
collections.OrderedDict 可以有序
Python 3.7才保證了順序。
(2)Dictionary別名
Associative arrays
Associative arrays, also known as maps, dictionaries, or hash maps in various programming languages, refer to a data structure that associates keys with values. In Python, this concept is implemented through dictionaries, where each key-value pair allows efficient lookup and retrieval of values based on unique keys.
2. 修改值:
修改position
lst=list()
lst.append(21)
lst.append(183)
lst[0]=23
print(lst)
修改label
ddd=dict()
ddd['age']=21
ddd['course']=183
ddd['age']=23
print(ddd)
3. 計(jì)算名字出現(xiàn)次數(shù)
counts=dict()
names=['csev','cwen','csev','zqian','cwen']
for name in names:
if name not in counts:
counts[name]=1
else:
counts[name]+=1
print(counts)
4. get()
if a key is already in a dictionary and assuming a default value if the key is not there
找不到就返回第二個(gè)參數(shù),To provide a default value if the key is not found
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)
這里 counts.get(name, 0) 返回 name 對(duì)應(yīng)的值,如果 name 不在字典中,返回默認(rèn)值 0。然后將這個(gè)值加 1,最后將結(jié)果存儲(chǔ)回字典中。這樣就能得到每個(gè)名字出現(xiàn)的次數(shù)。
5. Dictionary and Files
先把句子split成words,然后再count。
counts=dict()
line=input('Please enter a line of text:')
words=line.split()
print(f'Words: {words}')
for word in words:
counts[word]=counts.get(word,0)+1
print(f'Counts:{counts}')
6. Retrieving lists of keys and values
The first is the key, and the second variable is the value.
jjj={'chunck':1,'fred':42,'jason':100}
print(list(jjj))
print(jjj.keys())
print(jjj.values())
print(jjj.items())
[‘chunck’, ‘fred’, ‘jason’]
dict_keys([‘chunck’, ‘fred’, ‘jason’])
dict_values([1, 42, 100])
dict_items([(‘chunck’, 1), (‘fred’, 42), (‘jason’, 100)])
7.items():產(chǎn)生tuples
items() 是 Python 字典(dictionary)對(duì)象的方法,用于返回一個(gè)包含字典所有鍵值對(duì)的視圖對(duì)象。這個(gè)視圖對(duì)象可以用于迭代字典中的所有鍵值對(duì)
8.計(jì)算文件中的名字次數(shù)最大值
name=input(‘Please enter a line of text:’)
handle=open(name)
#全部統(tǒng)計(jì)
counts=dict()
for line in handle:
words=line.split()
for word in words:
counts[word]=counts.get(word,0)+1
#計(jì)算最大
bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword,bigcount)
Chapter10 Tuples
1. Tuples Are Like Lists
-Tuples are another kind of sequence that functions much like a list
-they have elements which are indexed starting at 0
2. Tuples are immutable. (Same as strings)
#list
x=[9,8,7]
x[2]=6
print(x)
R: [9, 8, 6]
#String
y='ABC'
y[2]='D'
print(y)
TypeError: ‘str’ object does not support item assignment
#Tuples
z=(5,4,3)
z[2]=0
print(z)
TypeError: ‘tuple’ object does not support item assignment
3. 方法
(1)not to do (所有和change相關(guān)的)
.sort()
.append()
.reverse()
(2)其中,sort和sorted()不同:
列表用方法sort() 直接修改,不能用于元組。
函數(shù)sorted() 返回一個(gè)新的已排序的列表,不會(huì)修改原始可迭代對(duì)象??捎糜诹斜?、元組、字符串等。
for k,v in sorted(d.item()):
sorted in key order
對(duì)value進(jìn)行排序:
c={'a': 10, 'b': 1, 'c': 22}
tmp = list ()
# 將字典 c 的key,value調(diào)換,并轉(zhuǎn)換為元組.
for k, v in c.items():
tmp.append((v, k))
print(tmp)
#從大到小排序value
tmp = sorted(tmp,reverse=True)
print(tmp)
[(10, ‘a(chǎn)’), (1, ‘b’), (22, ‘c’)]
[(22, ‘c’), (10, ‘a(chǎn)’), (1, ‘b’)]
(v,k):元組的第一個(gè)元素是值(value),第二個(gè)元素是鍵(key)。
使用 sorted() 函數(shù)對(duì)列表 tmp 進(jìn)行排序,參數(shù) reverse=True 表示降序排序(從大到?。?。排序后的結(jié)果將存儲(chǔ)在列表 tmp 中。
簡(jiǎn)化:
c={'a': 10, 'b': 1, 'c': 22}
print(sorted([(v,k)for k,v in c.items()]))
(3)通用:index() 查找指定索引。
(4)可用:items():returns a list of (key, value) tuples.
4. more efficient
· memory use and performance than lists
· making “temporary variables”
· For a temporary variable that you will use and discard without modifying
(sort in place原地排序,指在排序過(guò)程中不創(chuàng)建新的對(duì)象,而是直接在現(xiàn)有的數(shù)據(jù)結(jié)構(gòu)中進(jìn)行排序。用于列表)
· We can also put a tuple on the left-hand side of an assignment statement文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-793388.html
(a,b)=(99,98)
print(a,b)
6.Comparable:
按順序比較,第一個(gè)數(shù)字一樣,第二個(gè)數(shù)字3更大。
print((0,2,200)<(0,3,4))
True
按字母前后。字母越靠前越小。
print(‘Amy’>‘Abby’)
True文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-793388.html
到了這里,關(guān)于Python Data Structures: Dictionary, Tuples的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!