Python Data Structures: Dictionary, Tuples

发布时间:2024年01月15日

Chapter9 Dictionary

1. list and dictionary

(1)顺序
List: 有序-linear collection of values that stay in order. (一盒薯片)
Dictionary: 无序-’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)

{‘age’: 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. 计算名字出现次数

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
找不到就返回第二个参数,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 对应的值,如果 name 不在字典中,返回默认值 0。然后将这个值加 1,最后将结果存储回字典中。这样就能得到每个名字出现的次数。

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():产生tuples

items() 是 Python 字典(dictionary)对象的方法,用于返回一个包含字典所有键值对的视图对象。这个视图对象可以用于迭代字典中的所有键值对

8.计算文件中的名字次数最大值

name=input(‘Please enter a line of text:’)
handle=open(name)

#全部统计
counts=dict()
for line in handle:
    words=line.split()
    for word in words:
        counts[word]=counts.get(word,0)+1

#计算最大
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相关的)
.sort()
.append()
.reverse()

(2)其中,sort和sorted()不同:
列表用方法sort() 直接修改,不能用于元组。
函数sorted() 返回一个新的已排序的列表,不会修改原始可迭代对象。可用于列表、元组、字符串等。

for k,v in sorted(d.item()):
sorted in key order

对value进行排序:

c={'a': 10, 'b': 1, 'c': 22}
tmp = list ()

# 将字典 c 的key,value调换,并转换为元组.
for k, v in c.items():
    tmp.append((v, k))
print(tmp)

#从大到小排序value
tmp = sorted(tmp,reverse=True)
print(tmp)

[(10, ‘a’), (1, ‘b’), (22, ‘c’)]
[(22, ‘c’), (10, ‘a’), (1, ‘b’)]

(v,k):元组的第一个元素是值(value),第二个元素是键(key)。
使用 sorted() 函数对列表 tmp 进行排序,参数 reverse=True 表示降序排序(从大到小)。排序后的结果将存储在列表 tmp 中。

简化:

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原地排序,指在排序过程中不创建新的对象,而是直接在现有的数据结构中进行排序。用于列表)
· We can also put a tuple on the left-hand side of an assignment statement

(a,b)=(99,98)
print(a,b)

6.Comparable:

按顺序比较,第一个数字一样,第二个数字3更大。
print((0,2,200)<(0,3,4))
True
按字母前后。字母越靠前越小。
print(‘Amy’>‘Abby’)
True

文章来源:https://blog.csdn.net/2301_80205209/article/details/135611246
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。