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开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.