PythonThinking_T3打卡

Task3总结:

本文分为X个部分,
首先是自测部分:1.辨析了list[]、dict{}、tuple()2.list[]自测 3.dict{}自测 4.兼具列表和字典的优点的orderdict
然后是常规部分,内容如下:
3.5 dict字典
对比list,字典更是一种索引
3.6 tuple元组
对比list列表,tuple内的元素不能更新
3.7 bool布尔类型
3.8 读写文件//这是重难点,如:from sys import argv

#辨析:dict{}、list[]、tuple()
#总结
#list[] compare dict{}
#从数据结构角度:dict使用哈希表,list和tuple用链表顺序存储的
#dict: 优点: 查找和插入的速度极快,不会随着key的增加而变慢 缺点:需要占用大量内存,内存浪费多
#list:缺点:查找和插入时间会随着元素的增加而增加 优点:占用空间小,浪费内存空间少

#tuple() compare list[]:tuple内的元素不允许更新
#//小技巧:help(dict)
list = ['a',1,1.5,1+2,'1']
print(list)
dict = {'a':'A',1:'1',1+2:'3'}
print(dict)
print(dict['a'])#前 can call后
# print(dict['A'])#back can't call forward

tuple = ('a',1,1.5,1+2,'1')
print(tuple)
#tuple() compare list[]:tuple内的元素不允许更新
list[0]='A'
print(list)
# tuple[0]='A'
# print(tuple)
['a', 1, 1.5, 3, '1']
{'a': 'A', 1: '1', 3: '3'}
A
('a', 1, 1.5, 3, '1')
['A', 1, 1.5, 3, '1']
#自测list
list = ['a',1,1.5,1+2,'1']
tinylist=[123,'123']
print(list)               #输出完整列表
print(list[0])            # 输出列表的第一个元素
print(list[1:3])           # 输出第二个至第三个元素 
print(list[2:])            # 输出从第三个开始至列表末尾的所有元素
print(tinylist * 2)        # 输出列表两次
print(list + tinylist)     # 打印组合的列表
['a', 1, 1.5, 3, '1']
a
[1, 1.5]
[1.5, 3, '1']
[123, '123', 123, '123']
['a', 1, 1.5, 3, '1', 123, '123']
#自测dict
dict = {'a':'A','1':1,1+2:'3'}
#operation on dict
#add
dict['add']='+'
print(dict['add'])
print(dict,'\n')
#change-value
print(dict['a'])
dict['a']='have changed'
print(dict['a'],'\n')

#del
del dict['add']
print(dict,'\n')
+
{'a': 'A', '1': 1, 3: '3', 'add': '+'} 

A
have changed 

{'a': 'have changed', '1': 1, 3: '3'} 

#课外补充
#兼具列表和字典的主要优点(在将信息关联起来的同时保留原来的顺序)
#PY cc 9.5 Python标准库
from collections import OrderedDict
#从collection模块导入OrdereDict类
favorite_languages = OrderedDict()
#实例化,调用OrderedDict() 来创建一个空的有序字典,
#并将其存储在favorite_languages 中
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'

for name, language in favorite_languages.items():
      print(name.title() + "'s favorite language is " +
          language.title() + ".")

Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
#Task 3
#5字典dict
#list-compare:
things=[0+2,"b",1.2,'d']
print(things[0])
print(things[1])
things[0]='A'
print(things)
#dict
stuff={'name':'Zed','age':39,'height':6*12+2}
print(stuff)
# print(stuff[1])
#?索引的问题:区别于数组,这里是建立映射关系
print(stuff['name'])
stuff['city']='SF'#dict添加
print(stuff['city'])
print(stuff)
stuff[1] = "Wow"#dict添加
print(stuff[1])
print(stuff)
del stuff['city']#dict删除
del stuff[1]
print(stuff)
2
b
['A', 'b', 1.2, 'd']
{'name': 'Zed', 'age': 39, 'height': 74}
Zed
SF
{'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF'}
Wow
{'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF', 1: 'Wow'}
{'name': 'Zed', 'age': 39, 'height': 74}
#尝试自己写一个中国省份与省份缩写对应的字典代码
#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'])

# 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
# Sates:Michigan:MI→cities:MI:Detroit
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
and has city Portland
Florida state is abbreviated FL
and has city Jacksonville
California state is abbreviated CA
and has city San Francisco
New York state is abbreviated NY
and has city New York
Michigan state is abbreviated MI
and has city Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist
#3.6 元组tuple
#compare_list
import sys
tuple=('runoob',786,2.23,'john',70.2)
list=['runoob',786,2.23,'john',70.2]
tinylist=[123,'john']
tinytuple=(123,'john')
print(list)
print(tuple)
print(list[0])
print(tuple[0])
print(list[1:3])#输出第二个至第四个(不包含)元素
print(tuple[1:3])
print(list[2:])
print(tuple[2:])
print(tinylist*2)
print(tinytuple*2)
print(list+tinylist)
print(tuple+tinytuple)
['runoob', 786, 2.23, 'john', 70.2]
('runoob', 786, 2.23, 'john', 70.2)
runoob
runoob
[786, 2.23]
(786, 2.23)
[2.23, 'john', 70.2]
(2.23, 'john', 70.2)
[123, 'john', 123, 'john']
(123, 'john', 123, 'john')
['runoob', 786, 2.23, 'john', 70.2, 123, 'john']
('runoob', 786, 2.23, 'john', 70.2, 123, 'john')
# #以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000    # 元组中是非法应用
list[2] = 1000     # 列表中是合法应用
False and True
False or True
False and True
False
#参考PYHDW exe13参数、解包、变量
from sys import argv
script,first,second=argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
#print("Your third variable is:", third)
print('-'*10)
a=sys.argv
print(a)
a=sys.argv[0]#.py程序
print(a)
a=sys.argv[1]
print(a)
a=sys.argv[2]
print(a)
The script is called: F:\ProfessionalSoftware\Anaconda\lib\site-packages\ipykernel_launcher.py
Your first variable is: -f
Your second variable is: C:\Users\lx2019\AppData\Roaming\jupyter\runtime\kernel-cd60482b-136d-42ed-ad43-13a51e9934c3.json
----------
['F:\\ProfessionalSoftware\\Anaconda\\lib\\site-packages\\ipykernel_launcher.py', '-f', 'C:\\Users\\lx2019\\AppData\\Roaming\\jupyter\\runtime\\kernel-cd60482b-136d-42ed-ad43-13a51e9934c3.json']
F:\ProfessionalSoftware\Anaconda\lib\site-packages\ipykernel_launcher.py
-f
C:\Users\lx2019\AppData\Roaming\jupyter\runtime\kernel-cd60482b-136d-42ed-ad43-13a51e9934c3.json

python报错:
ValueError: not enough values to unpack (expected 3, got 2)
分析:这个错误的信息是,期望有三个返回值,但其实函数只有两个返回值
解决方法,检查函数和接收函数返回值的参数个数是否一致,改成一致即可

————
笨方法学python:from sys import argv 相关问题回答
1.对于 from sys import argv 的解释
对于该串代码的解释:
链接: [https://www.cnblogs.com/aland-1415/p/6613449.html#!comments]
sys.argv是从程序外部获取参数的桥梁,可以看作是一个列表,其第一个元素是程序本身,随后才依次是外部给予的参数
2.在学习python书籍的习题13中,遇到error问题
2.1 not enough values to unpack
2.2 need more than 1 value to unpack

//每当我遇到问题的时候就借助baidu,csdn,博客园这些。现在最主要还是谷歌要用的多,百度最差其次csdn总是跳来跳去也找不到答案,博客园如果有答案的话内容感觉还可以csdn挑来挑去没找到解决办法很烦人不过也好用。谷歌报错代码挺方便的,容易检索出来比较相似的问题。

#参考PYHDW exe14
from sys import  argv
script,user_name=argv
prompt='>'#
print(script)
print(user_name)
print("Hi",user_name"I'm the script:",script)

  File "<ipython-input-22-c786d2c1829e>", line 6
    print("Hi",user_name"I'm the script:",script)
                       ^
SyntaxError: invalid character in identifier
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')
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()
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-6-8d39f2141e1b> in <module>
      1 from sys import argv
----> 2 script, filename = argv
      3 print(f"We're going to erase {filename}.")
      4 print("If you don't want that, hit CTRL-C (^C).")
      5 print("If you do want that, hit RETURN.")


ValueError: too many values to unpack (expected 2)

ValueError: too many values to unpack (expected 2)

总结:这里卡了很久,是因为编译环境的问题,其实是可以跳过的

  • close - 关闭文件,就像编辑器中的 “文件->另存为”一样。
  • read - 读取文件内容。你可以把读取结果赋给一个变量。
  • readline - 只读取文本文件的一行内容。
  • truncate - 清空文件。清空的时候要当心。
  • write(‘stuff’) - 给文件写入一些“东西”。
  • seek(0) - 把读/写的位置移到文件最开头。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值