Python -- 列表 list、字典 dictionary

目录

列表(list)

字典 (Dictionary)


列表处理的是成组的信息,字典处理的是成对的数据。

列表(list)

列表(list)和元组(tuple)一样,都是序列,但列表是可变的(mutable),可以被修改。因此列表不仅可以做元组能做的事情,还能做元组不能做的事情。

学习元组的时候写过一个hero's_inventory的小程序,下面代码将其修改为用list

python 复制代码
# Hero's Inventory 2.0
# 演示列表List

# 创建一个带有一些元素的列表,然后for循环显示出来
inventory = ["sword", "armor", "shield", "healing potion"]
print("Your items: ")
for item in inventory: 
	print(item)

input("\nPress the enter key to continue")

# 使用len函数,获取列表的长度
# 这里要注意len()函数返回的是一个数字,不可以用加号"+"和字符串拼接,用的是",".
print("You have", len(inventory), "items in your possession.")

input("\nPress the enter key to continue")

# 利用in测试成员关系
if "healing potion" in inventory:
	print("You will live to fight another day.")

# 对列表进行索引,通过索引项显示列表
index = int(input("\nEnter the index number for an item in inventory: "))
print("At index", index, "is", inventory[index])

# 对列表进行切片,显示切片
start = int(input("\nEnter the index number to begin a slice: "))
finish = int(input("\nEnter the index number to end the slice: "))
print("inventory[", start, ":", finish, "] is", end = " ")
print(inventory[start:finish])

input("\nPress the enter key to continue")

# 对列表进行连接
chest = ["gold", "gems"]
print("You find a chest which contains:")
print(chest)
print("You add the contents of the chest to your inventory.")
inventory += chest
print(inventory)

input("\nPress the enter key to continue")

# 列表是可变序列,可通过索引进行赋值或修改
print("You trade your sword for a crossbow.")
# 会将原来 index 为0 位置的sword替换为 crossbow. 
inventory[0] = "crossbow"
print("Your inventory is now:")
print(inventory)

input("\nPress the enter key to continue.")

# 通过切片对列表进行赋值
print("You use your gold and gems to buy an orb of future telling.")
# 会把 inventory[4]和inventory[5]这两项替换为字符串"orb of future telling",列表长度会缩短1个单位
inventory[4:6] = ["orb of future telling"]
print("Your inventory is now:")
print(inventory)

input("\nPress the enter key to continue.")

# 删除列表元素
# del删除,使用索引删除
print("In a great battle, your shield is destoryed.")
# 索引2位置的元素"shield"会被删除,列表长度减1
del inventory[2]
print("Your inventory is now:")
print(inventory)

input("\nPress the enter key to continue.")

# del 删除列表切片
print("Your crossbow and armor are stolen by thieves.")
# 删除 inventory[0]和inventory[1],列表长度减2
del inventory[:2]
print("Your inventory is now:")
print(inventory)

input("\nPress the enter key to continue.")

列表的创建

列表名称 = [] # 创建空列表

列表名称 = list() #创建空列表

列表名称 = [ "Hello python", 3, ("Mike", 30)] # 创建带内容的列表

回忆一下元组的创建:

元组名称 = ()#创建空元组

元组名称 = ( 1, "complexion",{"username": "liu", "age": 30})# 创建带元素的元组

创建列表

inventory = ["sword", "armor", "shield", "healing potion"]

获取列表长度

len(inventory)

判断是否列表元素

if "healing potion"in inventory:

print("You will live to fight another day.")

通过索引获取列表元素

inventory[0] # 获取下标为0的列表元素

修改列表元素,

注意:只能修改列表中已存在的元素,如果修改一个不存在的下标元素会报错

会将原来 index 为0 位置的元素替换为 crossbow.

inventory[0] = "crossbow"

inventory[4] = "degger" # inventory 只有四个元素,inventory[4]不存在会报错

对列表元素切片

inventory[start:finish]

通过切片修改列表元素

将 inventory[2]和inventory[3]这两项替换为字符串"orb of future telling",

列表长度会缩短1个单位

inventory[2:4] = [ "orb of future telling"]

**"+"**连接列表

将chest列表中的数据添加到inventory中

chest = ["gold", "gems"]

inventory**+=** chest

**del(index)**函数,通过索引删除列表元素

删除下标2处的元素,列表长度减1

del inventory[2]

remove(value),删除列表中第一次出现的value

该方法从0开始对列表进行遍历以搜寻指定的值,当找到第一个element值时,将其从列表中删除。如果有多个element值,也只有一个会被删除,列表长度减1

删除59这个值,列表长度减1

scores.remove(59)

pop([i]),返回位置i的元素,并将其从列表中删除。也可以不指定位置编号,这样的话,被删除并返回的就是列表的最后一个元素

current_valule的值为下标2 位置的值,同时该值被删除

current_value = scores.pop(2)

append(value),将value添加到列表尾部

在scores列表中添加个87。列表长度加1

scores.append(87)

extend(value),将value追加到列表尾部

scores.extend(89)

区别与append的是,当追加一个字符串时,比如在names列表中追加一个字符串"liu"

names.append("liu") # "liu"作为一个整体添加到names中 names列表最后一个元素是 liu

names.extend("liu") # "liu"会被分解为"l""i""u"三个字符串追加到name中

insert(i, value),将value插入到位置i

将值76插入到scores列表下标为2的位置,之前2位置的值下标变为3,依次类推

scores.insert(2,76)

count(value),返回value出现的次数

show_times为87在scores列表中出现的次数

show_times = scores.count(87)

sort(),对元素进行排序,小值在前。可以使用reverse参数设置一个布尔值,设置为True,则列表倒序,大值在前。

对列表scores中的元素升序排序,1,2,3,4..

scores.sort()

对列表scores中的元素降序排序,4,3,2,1...

scores.sort(reverse=True)

reverse(),反转列表的顺序。区别与sort, 该函数是将列表元素的顺序反转

比如scores中原来是[1,2,5,4,3],reverse后呢就是[3,4,5,2,1]了

scores.reverse()

index(value), 返回value第一次出现的位置编号

60在scores列表中第一次出现的位置

scores.index(60)

clear(),清空列表

scores.clear()

下面是书中的Hight Scores游戏的代码, 利用列表方法来创建和维护一款计算机游戏的最高得分表,该游戏用到一个菜单驱动的简单界面,用户可以做一些选择: 添加新的分、删除得分、对得分记录进行排序、退出程序

python 复制代码
# High Scores
# 演示列表方法

# 定义一个空的分数列表
scores = []
# 定义变量,用于记录用户的选择
choice = None

# 显示菜单,除非用户输入0 ,否则菜单一直循环
while choice != "0": 
	print(
		"""
		High Scores

		0 - Exit
		1 - Show Scores
		2 - Add a Score
		3 - Remove a Score
		4 - Sort Scores
		"""
		)
	choice = input("Choice: ")
	print()

	# 退出程序
	if choice == "0":
		print("Good-bye.")
	# choice == 1 show scores 显示得分
	# 列出最高得分表
	elif choice == "1": 
		print("Highe Scores")
		for score in scores:
			print(score)
	# choice == 2 add a score 添加得分,scores列表长度加1
	# append(element)
	elif choice == "2":
		score = int(input("What score did you get?: "))
		scores.append(score)
	# choice == 3 remove score 删除得分
	# remove(element) 从0开始对列表进行遍历以搜寻指定的值,当找到第一个element值时,将其从列表中删除。
	# 如果有多个element值,也只有一个会被删除,列表长度减1
	elif choice == "3":
		score = int(input("Remove which score?: "))
		if score in scores:
			scores.remove(score)
		else:
			print(score, "isn't in the high scores list.")
	# choice == 4 sort scores 对列表进行排序
	# sort()默认排列顺序是升序 小到大; sort(reverse=True)设置排序方式为降序 大到小
	elif choice == "4":
		scores.sort(reverse=True)
	# 处理无效选项
	else:
		print("Sorry, but", choice, "isn't a valid choice.")

input("\n\nPress the enter key to exit.")

我们知道元组和列表可以存放任何类型的数据,那么,它们里面也可以含有元组或列表,这种列表(或元组)里面含有列表(或元组)的序列叫做嵌套序列(nested sequences)。

上面Hight Scores游戏里面,只有一个分数列表,一般情况下每个得分都会对应一个人对吧(谁得了积分,就记录一下),这就要用到嵌套序列了,High Scores2.0就来实现一下,然后会自动对分数进行排序,还会限制列表中只含有5条得分记录。

python 复制代码
# High Scores 2.0
# 演示嵌套序列

# 定义分数列表
scores = []

# 定义变量,用于记录用户的选择
choice = None

# 显示菜单,除非用户输入0 ,否则菜单一直循环
while choice != "0": 
	print(
		"""
		High Scores 2.0

		0 - Quit
		1 - List Scores
		2 - Add a Score
		"""
		)
	choice = input("Choice: ")
	print()

	# 退出程序
	if choice == "0":
		print("Good-bye.")

	# choice == 1 show scores 显示得分
	# 列出最高得分表
	elif choice == "1": 
		print("Highe Scores\n")
		print("NAME\tSCORE")
		for entry in scores:
			# 这里用到了序列的解包
			score, name = entry
			print(name, "\t", score)
	# choice == 2 add a score 添加得分,scores列表长度加1
	# append(element)
	elif choice == "2":
		name = input("What is th player's name?: ")
		score = int(input("What score did you get?: "))
		# 利用 name和score创建一个元组 entry.把分数放在元组的第一个位置,目的是希望这些条目能以先分数后名字的方式进行排序
		entry = (score, name)
		scores.append(entry)
		scores.sort(reverse=True)
		# 使用切片和赋值操作,目的是只保留最高的5条得分记录
		scores = scores[:5]
	else:
		print("Sorry, but", choice, "isn't a valid choice.")

input("\n\nPress the enter key to exit.")

创建嵌套数组

格式

nested = ["first", ("second", "third"), ["fourth", "fifth", "sixth"]]

如果想以先分数再名字排序,记得要把分数放在前面

scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)]

使用索引,访问嵌套元素

>>> print(scores[0])

('Moe', 1000)

访问元组内部的元组

>>> a_score = scores[2]

>>> print(a_score)

('Curly', 3000)

>>> print(a_score[0])

Curly

更为简单的方式是,使用两重索引

>>> print(scores[2][0])

Curly

理解序列的解包(unpacking)

如果已经知道序列中有多少个元素,就可以在一行代码中将他们分别赋值给相应的变量:

>>>name, score = ("Shemp", 175)

>>> print(name)

Shemp

>>> print(score)

175

解包对任何序列类型都有效。但要记住,变量的数量要跟序列中元素的数量相等,否则会产生错误。

字典 (Dictionary)

如果学过java可以将其理解为Map,就是键值对(key-value)形式,将数据成对存储。JSON格式的数据也是这种键值形式,哦,对了,Redis也是一种键值(key-value)型的缓存型数据库。

先说一下创建字典时,需要注意的事情:

  • 字典中不能含有多个具有相同键的字典项,即键唯一
  • 键必须是不可变的(immutable),可以是字符串、数字、元组。
  • 值不必唯一,且既可以是可变的(mutable)也可以是不可变的(immutable)

创建字典:

dic_name = { "key1": "value1", "key2": "('value2',value3)" }

通过键获取值

dic_name.get("key1") # 可以获取到key1对应的值value1

不存在的键会引发错误,在拿到key之后最好先对key进行一下校验, 使用in运算符

if "key3"in dic_name:

print(dic_name.get("key3")

else:

print("error, key3 is not exist")

get()方法有一个内建的安全机制用来处理"通过不存在的键获取值"的情况,即键不存在,就返回一个默认值,具体形式 get(key, [default]) 用法如下

dic_name**.get("key4", "you know that, I am default.")**# 第二个参数即设置的默认值

key不存在时,若设置了默认值 返回的就是默认值,没有设置就返回None;如果key存在,默认值会被覆盖。

添加一个键值对,使用赋值的形式(这里与java比较不同,java使用的是map.put(key,value))

dic_name[new_key] = "Now, you know how to add a item."

修改一个键值对的值

dic_name[exist_key] = "Now, you know how to redefine a item"

删除一个键值对

注意:通过不存在的键删除字典项(item)会引发错误,所以删除前最好先判断一下键是否存在

del dic_name[exit_key]

需要注意的是,字典不可以通过值(value)来获取键(key)

keys(),返回字典中的所有键的视图

dic_name.keys() # 返回所有键视图

values(),返回字典中的所有值的视图

dic_name.values() # 返回所有值视图

items(),返回字典中的所有字典项(item)的视图。

字典项可以理解为java map中的entry,即字典中的一对

dic_name.items() # 返回所有字典项视图
简单理解:

字典项视图(由keys(), values(),items()返回的),跟列表差不多(可以被for循环迭代),但它们不是列表(不能被索引,keys[0]不行)。视图是动态的,它们的内容不是独立与字典之外的,对字典的修改会反映到它的视图上。

一个简单小栗子,展示对字典的使用。

python 复制代码
'''
Geet Translator
帮助人们更好的理解现实生活中的技术爱好者。
该程序会创建一个由计算机词汇及其定义所组成的字典,然后用户可以对字典进行添加、修改、删除等

演示字典用法
'''

# 定义词汇字典
geek = {"404": "clueless. From the web error message 404, meaning page not found.",
			"Googling": "searching the Internet for background information on a person",
			"keyboard": "the collection of debris found in computer keyboards.",
			"Link Rot": "the process by which web page links become obsolete.",
			"Percussive Miantenance": "the act of striking an electronic device to make it work.",
			"Uninstalled": "being fired. Escpecially popular during the dot-bomb era."
		}

# 定义变量,用于存储用户的选择			
choice = "None"

# while 循环,直到用户输入0,计算机say bye
while choice != "0": 

	print(
	"""
	Greek Translator

	0 - Quit	
	1 - Look Up a Greek Term
	2 - Add a Greek Term
	3 - Redefine a Greek Term
	4 - Delete a Greek Term
	"""
	)

	choice = input("Choices: ")
	print()

	#退出
	if choice == "0":
		print("Good-bye.")

	# 得到定义
	elif choice == "1":
		# 用户输入键
		term = input("What term do you want me to translate?: ")
		if term in geek:
			definition = geek[term]
			print("\n", term, "means", definition)
		else:
			print("\nSorry, I don't know", term)
	# 添加一对新"术语/定义"
	elif choice == "2": 
		# 用户输入键
		term = input("What term do you want me to add?: ")
		if term not in geek:
			# 用户输入值
			definition = input("\nWhat's the definition?: ")
			# 将definition赋值给term
			geek[term] = definition
			print("\n", term, "has been added")
		else:
			prnt("\nThat term already exists! Try redefining it.")
	# 修改已经存在的词汇
	elif choice == "3":
		term = input("What term do you want me to redefine?: ")
		if term in geek:
			definition = input("What's the new definition?: ")
			# 新定义会替换掉旧的
			geek[term] = definition

		else:
			print("\nThat term doesn't exist! Try adding it.")
	# 删除一对"词汇/定义"
	elif choice == "4":
		term = input("What term do you want me to delete?: ")
		if term in geek:
			del geek[term]
			print("\nOk, I deleted", term)
		else:
			print("\nI can't no that!", term, "doesn't exist in the dictionary.")
	# 未知选型
	else:
		print("\nSorry, but", choice, "isn't a valid choice")

	
input("\n\nPress the enter key to exit.")
相关推荐
陳10302 小时前
C++:list(2)
开发语言·c++
小北方城市网2 小时前
SpringBoot 集成消息队列实战(RabbitMQ/Kafka):异步通信与解耦,落地高可靠消息传递
java·spring boot·后端·python·kafka·rabbitmq·java-rabbitmq
技术小黑2 小时前
TensorFlow学习系列02 | 实现彩色图片分类
python·机器学习·tensorflow
独行soc2 小时前
2026年渗透测试面试题总结-2(题目+回答)
android·java·网络·python·安全·web安全·渗透测试
写代码的【黑咖啡】2 小时前
Python中的BeautifulSoup:强大的HTML/XML解析库
python·html·beautifulsoup
草莓熊Lotso2 小时前
Linux 命令行参数与环境变量实战:从基础用法到底层原理
linux·运维·服务器·开发语言·数据库·c++·人工智能
李守聪2 小时前
小程序定制,我的实践复盘分享
python
枫叶丹42 小时前
【Qt开发】Qt系统(七)-> Qt网络安全
c语言·开发语言·c++·qt·网络安全
草莓熊Lotso2 小时前
Qt 控件核心入门:从基础认知到核心属性实战(含资源管理)
运维·开发语言·c++·人工智能·后端·qt·架构