Python Data Structures: Dictionary, Tuples

这篇具有很好参考价值的文章主要介绍了Python Data Structures: Dictionary, Tuples。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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://www.toymoban.com/news/detail-793388.html

到了这里,关于Python Data Structures: Dictionary, Tuples的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Python】成功解决ValueError: dictionary update sequence element #0 has length 1; 2 is required】

    【Python】成功解决ValueError: dictionary update sequence element #0 has length 1; 2 is required】 🌈 个人主页:高斯小哥 🔥 高质量专栏:Matplotlib之旅:零基础精通数据可视化、Python基础【高质量合集】、PyTorch零基础入门教程👈 希望得到您的订阅和支持~ 💡 创作高质量博文(平均质量分9

    2024年03月10日
    浏览(60)
  • 如何在 Python 中读取 .data 文件?

    创建.data文件是为了存储信息/数据。 此格式的数据通常以逗号分隔值格式或制表符分隔值格式放置。 除此之外,该文件可以是二进制或文本文件格式。在这种情况下,我们将不得不找到另一种访问它的方式。 在本教程中,我们将使用.csv文件,但首先,我们必须确定文件的内

    2024年02月07日
    浏览(23)
  • 使用Python编程语言处理数据 (Processing data using Python programm

    作者:禅与计算机程序设计艺术 Python作为一种高级、开源、跨平台的编程语言,已经成为当今最流行的数据分析和机器学习工具。本文介绍了使用Python编程语言处理数据的一些基础知识,如列表、字典、集合、迭代器等,并对pandas、numpy、matplotlib、seaborn等数据分析库进行了

    2024年02月07日
    浏览(36)
  • python-用form-data形式上传文件请求

    虽然现在基本上都约定俗成的接口都用json形式请求 但是不可避免地 有些接口需要传文件流,此时就需要用form-data形式上传了 for.e: 存在以下接口,通过接口创建海报图 但需要上传缩略图, 此时接口的Content-Type就不能是application/json,而是multipart/form-data; 参数格式也是以表单

    2023年04月08日
    浏览(34)
  • Python Packages for Big Data Analysis and Visualization

    作者:禅与计算机程序设计艺术 Python第三方库主要分为两类:数据处理、可视化。下面是用于大数据分析与可视化的常用的Python第三方库列表(按推荐顺序排序): NumPy: NumPy 是用 Python 编写的一个科学计算库,其功能强大且全面,尤其适用于对大型多维数组和矩阵进行快速

    2024年02月07日
    浏览(37)
  • python + request实现multipart/form-data请求上传文件

    1、multipart/form-data介绍         multipart/form-data 是 HTTP 协议中用于上传文件的一种类型。它允许客户端向服务器发送文件以及一些额外的元数据(例如文件名、MIME 类型、图片等)。这种类型的请求不同于普通的application/x-www-form-urlencoded 格式,其中数据是在请求体中进行编

    2024年02月11日
    浏览(32)
  • requests 库:发送 form-data 格式的 http 请求 (python)

    requests官方网站地址 requests_toolbelt Python自动化 requests 库:发送 form-data 格式的 http 请求 requests-toolbelt · PyPI

    2024年02月03日
    浏览(42)
  • Python报错:TypeError: Cannot interpret ‘1‘ as a data type

    在使用np.zeros()创建新数组的时候,我传入的参数是如下代码: 运行报错: 报错原因是我们给zeros()函数传入的参数发生问题: 我传入的参数是(layers_dims[l],1),这是不对的,因为zeros只需要传入一个参数,就是shape。所以我们应该更改为: 把(layers_dims[l],1)用括号括起来

    2024年02月13日
    浏览(32)
  • 相关性分析——Pearson相关系数+热力图(附data和Python完整代码)

    相关性分析:指对两个或多个具有相关性的变量元素进行分析 相关系数最早是由统计学家卡尔 皮尔逊设计的统计指标,是研究变量之间线性相关承兑的值,一般用字母 r 表示。 Pearson相关系数是衡量两个数据集合是否在一条线上面,用于衡量变量间的线性关系。 这里是引用

    2024年02月05日
    浏览(30)
  • Python 实现http server接收mutipart/form-data文件 方法1

    PostMan生成Python 代码: 代码基本功能 :实现将客户端发送的文件转发到本地。 代码中的打印 :为了调试方便代码中增加了一些关于boudary的打印。 代码中的自定义字段 :代码中的 ‘file’ 就是postman客户端请求中的文件名称。

    2024年02月07日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包