Python Data Structures: Dictionary, Tuples

2024-01-16 04:20

本文主要是介绍Python Data Structures: Dictionary, Tuples,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • Chapter9 Dictionary
    • 1. list and dictionary
    • 2. 修改值:
    • 3. 计算名字出现次数
    • 4. get()
    • 5. Dictionary and Files
    • 6. Retrieving lists of keys and values
    • 7.items():产生tuples
    • 8.计算文件中的名字次数最大值
  • Chapter10 Tuples
    • 1. Tuples Are Like Lists
    • 2. Tuples are immutable. (Same as strings)
    • 3. 方法
    • 4. more efficient
    • 6.Comparable:

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]=1else: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) + 1print(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 = wordbigcount = 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

这篇关于Python Data Structures: Dictionary, Tuples的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/611329

相关文章

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Python如何精准判断某个进程是否在运行

《Python如何精准判断某个进程是否在运行》这篇文章主要为大家详细介绍了Python如何精准判断某个进程是否在运行,本文为大家整理了3种方法并进行了对比,有需要的小伙伴可以跟随小编一起学习一下... 目录一、为什么需要判断进程是否存在二、方法1:用psutil库(推荐)三、方法2:用os.system调用

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)

一文带你搞懂Python中__init__.py到底是什么

《一文带你搞懂Python中__init__.py到底是什么》朋友们,今天我们来聊聊Python里一个低调却至关重要的文件——__init__.py,有些人可能听说过它是“包的标志”,也有人觉得它“没... 目录先搞懂 python 模块(module)Python 包(package)是啥?那么 __in

使用Python实现图像LBP特征提取的操作方法

《使用Python实现图像LBP特征提取的操作方法》LBP特征叫做局部二值模式,常用于纹理特征提取,并在纹理分类中具有较强的区分能力,本文给大家介绍了如何使用Python实现图像LBP特征提取的操作方... 目录一、LBP特征介绍二、LBP特征描述三、一些改进版本的LBP1.圆形LBP算子2.旋转不变的LB