第3章——数学运算、字符串、文本、列表
1.字典
字典(Dictionary)是Python 中的另一种数据结构。字典(也叫 dict)是一种和列表类似的数据存储方式。但是不同于列表只能用数字获取数据,字典可以用任何东西来获取。可以把字典当成是一个存储和组织数据的数据库。
注:键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。另外,记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
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'])
# print some states,输出州名
print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])
# 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}")
下面是程序运行结果
NY State has: New York
OR State has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
Oregon is abbreviated OR
Florida is abbreviated FL
California is abbreviated CA
New York is abbreviated NY
Michigan is abbreviated MI
----------
CA has the city San Francisco
MI has the city Detroit
FL has the city Jacksonville
NY has the city New York
OR has the city Portland
----------
Oregon state is abbreviated OR
Florida state is abbreviated FL
California state is abbreviated CA
New York state is abbreviated NY
Michigan state is abbreviated MI
and has city Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist
这个例子是如何把州名和它们的缩写以及州的缩写和城市映射(mapping)起来的,记住,“映射”或者说“关联”(associate)是字典的核心理念。
2.元组
元组是另一个数据类型,类似于 List(列表)。
元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print(tuple) # 输出完整元组
print(tuple[0]) # 输出元组的第一个元素
print(tuple[1:3]) # 输出第二个至第四个(不包含)的元素
print(tuple[2:]) # 输出从第三个开始至列表末尾的所有元素
print(tinytuple * 2) # 输出元组两次
print(tuple + tinytuple) # 打印组合的元组
以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # 元组中是非法应用
list[2] = 1000 # 列表中是合法应用
3.布尔类型
在python表述的语法是,不再赘述
• and
• or
• not
• != (不等于)
• == (等于)
• >= (大于等于)
• <= (小于等于)
• True
• False
4.读写文件
- close - 关闭文件,就像编辑器中的 “文件->另存为”一样。
- read - 读取文件内容。你可以把读取结果赋给一个变量。
- readline - 只读取文本文件的一行内容。
- truncate - 清空文件。清空的时候要当心。
- write(‘stuff’) - 给文件写入一些“东西”。
- seek(0) - 把读/写的位置移到文件最开头。
通过上述命令我们可以一个小小的编辑器:
from sys import argv
script, filename = argv
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') #读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
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()
需要在运行之前设置文件名,也就是传参
运行结果如下:
同时,在本项目文件的目录下生成文件text1.txt