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实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到