文章目录
前言
本篇内容主要介绍有关字典、元组、布尔类型和读写文件的相关内容。
一、字典
字典(也叫 dict)是一种和列表类似的数据存储方式。但是不同于列表只能用数字获取数据,字典可以用任何东西来获取。你可以把字典当成是一个存储和组织数据的数据库。
比较一下列表和字典的作用:
列表:
字典:
我们用了字符串(而不是数字)来从 stuff 字典中取出了我们想要的东西。我们也可以用字符串来给字典添加新的东西。而且,也可以不用字符串,我们可以这样做:
在这一段代码中我用了数字,所以你看,我在打印字典的时候既可以用数字也可以用字符串来作为键。我可以用任何东西。好吧,大多数东西,不过你现在就假装能够用任何东西吧。
当然,如果一个字典只能放东西那就太蠢了。下面是如何用 ‘del’ 关键词来删除其中的东西:
1.一个字典示例
把州名和它们的缩写以及州的缩写和城市映射(mapping)起来的,记住,“映射”或者说“关联”(associate)是字典的核心理念。
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])
# do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])
# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")
![在这里插入图片描述](https://www.icode9.com/i/ll/?i=046b95d4d47845acaf5917342a16783f.png?,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBATmV2ZXIgIGdpdmUgIHVw,size_10,color_FFFFFF,t_70,g_se,x_16#pic_center
写一个中国省份与省份缩写对应的字典代码:
# create a mapping of state to abbreviation
states = {
'北京市': '京',
'天津市': '津',
'上海市': '沪',
}
# create a basic set of states and some cities in them
cities = {
'辽': '辽宁',
'黑': '黑龙江',
'鲁': '山东'
}
# add some more cities
cities['京'] = '北京'
cities['沪'] = '上海'
cities['津'] = '天津'
# print out some cities
print('-' * 10)
print("京 State has: ", cities['京'])
print("沪 State has: ", cities['沪'])
# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")
二、元组
元组是另一个数据类型,类似于 List(列表)。
元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。
以下元组是无效的,因为元组是不允许更新的。而列表是允许更新的:
三、布尔类型
• and
• or
• not
• != (不等于)
• == (等于)
• >= (大于等于)
• <= (小于等于)
• True
• False
四、读写文件
close - 关闭文件,就像编辑器中的 “文件->另存为”一样。
read - 读取文件内容。你可以把读取结果赋给一个变量。
readline - 只读取文本文件的一行内容。
truncate - 清空文件。清空时要当心。
write(‘stuff’) - 给文件写入一些“东西”。
seek(0) - 把读/写的位置移到文件最开头。
用这些命令做一个小小的编辑器:
from sys import argv
filename = "test.txt"
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close()
课后练习及补充1(2&3章)
1.1 数据类型相关练习
1.1.1 数据类型转换
了解int(),float(),str(),type()等的用法。
将字符串’520’转化为小数,可以使用float():
了解字符串的切片操作:
1.2 列表操作
列表是个框,什么都可以往里装。
从lis里得到’sing’应该怎么做呢?
列表的元素是可以修改的:
将列表最后一个元素更改为50:
列表有一个非常好用的操作,叫list comprehension:
ord()的作用是返回符号的unicode编码。
1.3 元组操作
元组元素不可修改。
1.4 字典操作
字典元素可以更改。
1.5 Sets 集合
Sets are a methematical concept, they are a lot like dictionaries with keys but no corresponding values.
跟数学的概念很相似,类似于字典的键,但没有对应的值。
Sets are enclosed by curly braces, elements seperated by comma, ‘{’,’}’.
用花括弧。
Sets do not support indexing or slicing, and do not have inherent order.
不支持下标应用和切片。
1.6 运算和布尔运算
运算符 | 描述 | 实例 |
---|---|---|
= | 简单的赋值运算符 | c = a + b :将 a + b 的运算结果赋值为 c |
+= | 加法赋值运算符 | c += a 等效于 c = c + a |
-= | 减法赋值运算符 | c -= a 等效于 c = c - a |
*= | 乘法赋值运算符 | c *= a 等效于 c = c * a |
/= | 除法赋值运算符 | c /= a 等效于 c = c / a |
%= | 取模赋值运算符 | c %= a 等效于 c = c % a |
**= | 幂赋值运算符 | c **= a 等效于 c = c ** a |
//= | 取整除赋值运算符 | c //= a 等效于 c = c // a |
布尔运算和比较运算:
逻辑运算符
and or not
is 和 is not 运算符 与==以及!=的区别:
is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。
空值比较:
总结
本次任务主要讲解了字典、元组、布尔类型以及读写文件的基本操作以及一些实践练习。