Jamie's Blog

Talk is cheap, show me the code.

How to filter in list,set and dict

过滤掉列表中的负数【列表的三种方法】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#用列表生成式建立一个10到-10之间随机列表
from random import randint
data = [randint(-10,10) for i in range(10)]
print(data)

<!-- more -->

#方法一:for 循环
c = []
for i in data:
if i > 0:
c.append(i)
print(c)

#方法二:列表解析
d = [i for i in data if i > 0]
print(d)

#方法三:filter 函数
f = filter(lambda x:x > 0,data)
print(list(f))
[-6, 0, 4, -6, -7, 2, 9, -10, 2, 4]
[4, 2, 9, 2, 4]
[4, 2, 9, 2, 4]
[4, 2, 9, 2, 4]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#用字典生成式建立一个20人的字典
from random import randint
p = {i:randint(60,100) for i in range(1,21)}
print(p)
p ={1: 88, 2: 80, 3: 76, 4: 92, 5: 88, 6: 93, 7: 91, 8: 100, 9: 60, 10: 68, 11: 85, 12: 95, 13: 73, 14: 77, 15: 65, 16: 82, 17: 67, 18: 87, 19: 89, 20: 92}
#筛出字典中值高于90的项

#方法一:for 循环
h = {}
for k,v in p.items():
if v > 90:
h[k] = p[k]
print(h)

#方法二:字典解析

g = {k:v for k,v in p.items() if v>90}
print(g)
{1: 85, 2: 93, 3: 60, 4: 65, 5: 97, 6: 83, 7: 79, 8: 61, 9: 80, 10: 69, 11: 95, 12: 98, 13: 91, 14: 94, 15: 64, 16: 60, 17: 85, 18: 95, 19: 64, 20: 60}
{4: 92, 6: 93, 7: 91, 8: 100, 12: 95, 20: 92}
{4: 92, 6: 93, 7: 91, 8: 100, 12: 95, 20: 92}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#用列表生成式建立一个10个数的集合
s = set([randint(-10,10) for x in range(10)])
print(s)

#筛出集合中能被3整除的元素

#方法一:for 循环
n = set()#创建空集合
for i in s:
if i%3 == 0:
n.add(i)
print(n)

#方法二:列表解析
w = set([i for i in s if i%3 == 0])
w1 = {i for i in s if i%3 == 0}#和字典解析的区别在于前面没有冒号
print(w)
print(w1)
{2, 6, 9, -8, -7, -3, -1}
{9, -3, 6}
{9, -3, 6}
{9, -3, 6}

Shallowcopy and Deepcopy

赋值操作认识

1.赋值是将一个对象的地址赋值给一个变量,让变量指向该地址

2.修改不可变对象(str、tuple)需要开辟新的空间

3修改可变对象(list等)不需要开辟新的空间

浅拷贝( 新瓶装旧酒 )

浅拷贝仅仅复制了容器中元素的地址

浅拷贝是在另一块地址中创建一个新的变量或容器,但是容器内的元素的地址均是源对象的元素的地址的拷贝。也就是说新的容器中指向了旧的元素( 新瓶装旧酒 )

Mutable and Immutable

immutable指对象一经创建,即不可修改。对象是不是immutable取决于数据类型,比如

整型(integer)、字符串(string)和元组(tuple)都是immutable,

而列表(list)、字典(dictionary)、集合(set)都是mutable。

不可变的元祖 tuple (immutable)

tuple和list非常类似,但是tuple一旦初始化就不能修改

tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用索引,但不能赋值成另外的元素。

不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。

Scope in Python

Python中有作用域链,变量会由内到外找,先去自己作用域去找,自己没有再去上级去找,直到找不到报错

1
2
3
4
5
6
7
8
name = "lzl"
def f1():
name = "Eric"
def f2():
name = "Snor"
print(name)
f2()
f1()
Snor

Proudly powered by Hexo and Theme by Hacker
© 2019 Jamie