2021-03-12python学习笔记

2021-03-12python学习笔记

学习教程:https://www.cnblogs.com/daxiong2014/p/6598976.html

1、由于缩进问题导致的错误unexpected indent

  "This is a string"[4] 

代码图片
运行结果不造成影响:

"This is a string"[4]
Out[1]: ' '

在句子前会显示报错以及 unexpected indent,但是跑代码还是正常的,这是因为缩进出了问题,只需要把这一句前面的空格删掉就可以了。删完之后如下图:

在这里插入图片描述
最后运行的结果相同,不再赘述。

2、if可以当成表达式使用:

"yahoo!" if 3 > 2 else 2
Out[8]: 'yahoo!'


"yahoo!" if 2 > 2 else 2
Out[9]: 2

3、运用append在列表末尾添加元素

li=[]
li.append(1)
print(li)
li.append(1)
print(li)

结果:

li=[]
li.append(1)
print(li)
li.append(1)
print(li)
[1]
[1, 1]

4、运用pop移除列表最后一个元素

li=[1,2,3,4];
li.pop()
print(li)
li.pop()
print(li)

运行结果:

li=[1,2,3,4];
li.pop()
print(li)
li.pop()
print(li)
[1, 2, 3]
[1, 2]

5、使两种合并列表的方式(直接加和extend函数)

5.1 直接加

li=[1,2,3,4];
other_li=[5,6];
li+other_li
Out[43]: [1, 2, 3, 4, 5, 6]

特点是保留li和other_li的原值。

5.2 extend

li=[1,2,3,4];
other_li=[5,6];
li.extend(other_li)
li
Out[44]: [1, 2, 3, 4, 5, 6]
``
特点是合成的新的列表保存入li,即原列表被改变。

6、用in判断某一元素在不在列表中

li=[1,2,3,4,5,6]
1 in li
Out[49]: True

li=[1,2,3,4,5,6]
7 in li
Out[50]: False

7、元组和列表很像,但是元组不可变

tup=(0,1,2,3)
tup[0]=3

TypeError: 'tuple' object does not support item assignment
tup+(4,5,6)
Out[56]: (0, 1, 2, 3, 4, 5, 6)

id(tup)
Out[58]: 2021604106624

id(tup+(4,5,6))
Out[59]: 2021602601376

这样不意味着元组可变,因为存储的地方不一样(由内置函数id可以得到)

8、可以把元组(或列表)中的元素解包赋值给多个变量

当tup=(0,1,2,3)时

a,b,c,d=tup
a,b,c,d
Out[62]: (0, 1, 2, 3)

相当于把0赋值给a,1赋值给b,2赋值给c,3赋值给d。
但是,如果当tup=(0,1,2,3)时输入代码如下:

a,b,c=tup
Traceback (most recent call last):

  File "<ipython-input-60-e86a261c9c24>", line 1, in <module>
    a,b,c=tup

ValueError: too many values to unpack (expected 3)

意味着返回值个数和你接收参数的个数不一致,这里返回值的个数和tup的元素个数一样,是4个,但是接受参数为a、b、c,只有3个故报错。

如果省去了小括号,那么元组会被自动创建

d,e,f=4,5,6
d,e,f
Out[67]: (4, 5, 6)

9、删除元组总的元素

由于元组不可变,因此只能用重新组建一个元组的方式来“删除元组的元素”:

temp = ('龙猫', '泰迪', '小猪佩奇', '叮当猫')
temp = temp[:2] + temp[3:]
print(temp)
('龙猫', '泰迪', '叮当猫')

满足左闭右开,原因从参考https://www.jianshu.com/p/5eaa330788e8

10、元组内置函数

1、cmp(tuple1, tuple2):比较两个元组元素。
2、len(tuple):计算元组元素个数。
3、max(tuple):返回元组中元素最大值。
4、min(tuple):返回元组中元素最小值。
5、tuple(seq):将列表转换为元组。
此外,如果元组中只有一个数,则要在该数后加逗号(例如tup=(1,)),否则(tup=(1))会被定义为整数

11、字典用于存储映射

filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"]
Out[72]: 1

one->1,two->2,three->3
但是不是双射,所以会报错:

filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["1"]
Traceback (most recent call last):

  File "<ipython-input-70-59608d21aaf3>", line 2, in <module>
    filled_dict["1"]

KeyError: '1'

11.1 将字典的所有键名获取为一个列表

filled_dict.keys()
Out[73]: dict_keys(['one', 'two', 'three'])

请注意:无法保证字典键名的顺序如何排列。

11.2 将字典的所有键值获取为一个列表

filled_dict.values()
Out[75]: dict_values([1, 2, 3])

请注意:无法保证字典键名的顺序如何排列。

11.3 要使用 get 方法来避免键名错误

filled_dict.get("one")
Out[77]: 1

filled_dict.get("four")

11.4Setdefault 方法可以安全地把新的名值对添加到字典里

filled_dict.setdefault("five", 5) 
filled_dict
Out[80]: {'one': 1, 'two': 2, 'three': 3, 'five': 5}
filled_dict.setdefault("five", 6)
filled_dict
Out[81]: {'one': 1, 'two': 2, 'three': 3, 'five': 5}

12、{} 可以用来声明一个集合

用add把数加进集合
使用 & 来获取交集
使用 | 来获取并集
使用 - 来获取补集
使用 in 来检查是否存在于某个集合中

13、for循环遍历列表

方法一:

for animal in ["dog", "cat", "mouse"]:
    print("{} is a mammal".format(animal))
dog is a mammal
cat is a mammal
mouse is a mammal

方法二:

for animal in ["dog", "cat", "mouse"]:
    print ("%s is a mammal"%animal)
dog is a mammal
cat is a mammal
mouse is a mammal

在敲方法二的时候依次犯了以下几个错误:
①在print前没敲tab,由于Python严格地要求代码缩进,缩进的代码块相对于上一级是从属关系。会报错:expected an indented block
② print ("%s is a mammal"%animal) 第二次这里的括号忘记加,第三次括号加错位置(把%animal留在括号外面了),分别报错Missing parentheses in call to ‘print’. Did you mean print("%s is a mammal" % animal)? 和unsupported operand type(s) for %: ‘NoneType’ and ‘str’

for i in range(4):
    print(i)
0
1
2
3

14、使用 try/except 代码块来处理异常

426 try:
427     # Use raise to raise an error
428     # 使用 raise 来抛出一个错误
429     raise IndexError("This is an index error")
430     # 抛出一个索引错误:“这是一个索引错误”。
431 except IndexError as e:
432     pass    # Pass is just a no-op. Usually you would do recovery here.
433             # pass 只是一个空操作。通常你应该在这里做一些恢复工作。
434  

15、调用函数的两种方式

442 # 使用 def 来创建新函数
443 def add(x, y):
444     print "x is %s and y is %s" % (x, y)
445     # (译注:意为“x 是 %s 而且 y 是 %s”。)
446     return x + y    # Return values with a return statement
447                     # 使用 return 语句来返回值

add(5, 6) # 调用函数并传入参数
add(y=6, x=5) # 调用函数的另一种方式是传入关键字参数

add(5, 6)和add(y=6, x=5)都可以调用这个函数

16、定义一个函数,并让它接受可变数量的关键字参数

def varargs(*args):
     return args 

varargs=(1,2,3,4);

def keyword_args(**kwargs):
    return kwargs 

keyword_args(big="foot", loch="ness")
Out[99]: {'big': 'foot', 'loch': 'ness'}

17、使用 * 来展开元组,使用 ** 来展开关键字参数

def all_the_args(*args, **kwargs):
    print (args)
    print (kwargs)


args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
                    # 相当于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
                       # 相当于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
                              # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)
(1, 2, 3, 4)
{}
()
{'a': 3, 'b': 4}
(1, 2, 3, 4)
{'a': 3, 'b': 4}

##逐步输入的结果如下:

args = (1, 2, 3, 4)

kwargs = {"a": 3, "b": 4}

all_the_args(*args)
(1, 2, 3, 4)
{}

all_the_args(**kwargs)
()
{'a': 3, 'b': 4}

all_the_args(*args, **kwargs)
(1, 2, 3, 4)
{'a': 3, 'b': 4}

今天学习到第500条代码
明天看一下是把剩下的大概200条学完还是学习SQL,加油加油~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值