零基础学Python-Task03

本文介绍了Python中的字典数据结构,包括读写数据和删除数据的操作。还讲解了元组的概念,强调其不可变性。此外,讨论了布尔类型的逻辑运算,并通过实例展示了如何读写文件。最后,学习了字典遍历、文件操作和条件判断在实际编程中的应用。
摘要由CSDN通过智能技术生成

学习内容:

(一)字典

字典(也叫 dict)是一种和列表类似的数据存储方式。但是不同于列表只能用数字获取数据,字典可以用任何东西来获取。
读数据:
字典能够把一个东西和另一个东西关联起来,不管它们是什么类型。

stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}

print(stuff['name'])  # Zed

print(stuff['age'])   # 39

print(stuff['height'])  # 74

stuff['city'] = "SF"

print(stuff['city'])

print(stuff) # {'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF'}

写入数据

stuff[1] = "Wow"
stuff[2] = "Neato"
print(stuff[1]) # Wow

print(stuff[2]) # Neato

print(stuff)
# {'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF', 1: 'Wow', 2: 'Neato'}

删除数据

del stuff['city']
print(stuff) # {'name': 'Zed', 'age': 39, 'height': 74, 1: 'Wow', 2: 'Neato'}

例子

  • 字典取数据时可以嵌套,如:cities[states[‘Michigan’]]
  • 用for…in…遍历字典的每一个元素,states.items代表每一项 ,state代表第一个字符,abbrev代表第二个字符
  • 在字典里查找数据可以用get,第一个参数是名称,第二个参数是没有找到的返回值,cities.get(‘TX’, ‘Does Not Exist’) #如果在city里没有找到 TX ,就返回’Does Not Exist’
##############一个字典实例###############
# 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(cities)
#{'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville', 'NY': 'New York', 'OR': 'Portland'}

# print out some cities
print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])
# NY State has:  New York
# OR State has:  Portland


# print some states
print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])
# Michigan's abbreviation is:  MI
# Florida's abbreviation is:  FL

# do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])
# Michigan has:  Detroit
# Florida has:  Jacksonville


# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
    print(f"{state} is abbreviated {abbrev}")

# 用for...in...遍历字典的每一个元素,states.items代表每一项 ,state代表第一个字符,abbrev代表第二个字符
# Oregon is abbreviated OR
# Florida is abbreviated FL
# California is abbreviated CA
# New York is abbreviated NY
# Michigan is abbreviated MI



# 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') #如果在city里没有找到 TX ,就返回'Does Not Exist'
print(f"The city for the state 'TX' is: {city}")
# The city for the state 'TX' is: Does Not Exist

(二)元组

元组是另一个数据类型,类似于 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 )
tuple[2] = 1000    # 元组中是非法应用

在这里插入图片描述

(三)布尔类型

and :有一个为假,结果就为假
or: 有一个为真,结果才为真

True and True # True
False and True # False
1 == 1 and 2 == 1 # False
"test" == "test" # True
1 == 1 or 2 != 1  # True
 True and 1 == 1 # True
False and 0 != 0 # False
not ("testing" == "testing" and "Zed" == "Cool Guy") # True
1 == 1 and (not ("testing" == 1 or 1 == 0)) # True
"chunky" == "bacon" and (not (3 == 4 or 3 == 3)) # False
 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")) #False

Process finished with exit code 0

(四)读写文件

close - 关闭文件,就像编辑器中的 “文件->另存为”一样。
read - 读取文件内容。你可以把读取结果赋给一个变量。
readline - 只读取文本文件的一行内容。
truncate - 清空文件。清空的时候要当心。
write(‘stuff’) - 给文件写入一些“东西”。
seek(0) - 把读/写的位置移到文件最开头。
1.open
使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open(‘thefile.txt’)
2.读文件
读文本文件
input = open(‘data’, ‘r’)
#第二个参数默认为r
input = open(‘data’)
3.写文件
写文本文件
output = open(‘data’, ‘w’)

写二进制文件
output = open(‘data’, ‘wb’)

追加写文件
output = open(‘data’, ‘w+’)

写数据
file_object = open(‘thefile.txt’, ‘w’)
file_object.write(all_the_text)
file_object.close( )

总结:

task03:本次学习了字典、元组、布尔类型和文件操作,重要的是对字典的遍历;元组只能读不能写;and是有一个为假,结果就为假,or是有一个为真,结果才为真;最后是读写文件的一些操作,之后都会用到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你是零基础Python,我建议你从基础语法开始习。你可以先了解变量和常量的概念,习如何使用注释来提高代码的可读性。此外,了解Python的垃圾回收机制也是很重要的。\[1\] 一旦你掌握了基础语法,你可以Python的基本数据类型,如字符串、整数、浮点数等。习如何与用户进行交互,并习如何格式化输出。此外,你还可以了解Python的基本运算符,如加法、减法、乘法等。\[1\] 在掌握了基础语法和基本数据类型后,你可以习流程控制,如if判断语句、while循环和for循环。这些语句可以帮助你根据条件执行不同的代码块或重复执行特定的代码块。\[1\] 另外,了解Python中的可变和不可变类型以及深浅copy的概念也是很重要的。这些概念可以帮助你更好地理解Python中的数据类型。\[1\] 如果你想进一步Python的高级特性,你可以习函数的基本使用、函数参数、函数对象和函数嵌套等内容。了解名称空间和作用域的概念也是很重要的。此外,你还可以习闭包函数、装饰器、迭代器和生成器等内容。\[3\] 最后,你可以习模块的概念和如何使用模块来组织和管理代码。模块可以帮助你将代码分成不同的文件,并提供了一种方便的方式来重用代码。\[3\] 总之,对于零基础Python的人来说,建议从基础语法开始习,逐步深入习不同的概念和特性。同时,可以参考一些全面的习资料,如提到的那份资料,它包含了Python的各个方面的知识点,适合初习和查找知识点。\[2\] #### 引用[.reference_title] - *1* *2* *3* [python入门教程(非常详细),从零基础入门到精通,看完这一篇就够了](https://blog.csdn.net/Python_0011/article/details/122488652)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值