1.python 修改字典的key
dict={'a':1, 'b':2}
dict["c"] = dict.pop("a")
print(dict)
![](https://img.haomeiwen.com/i16627003/a11c643bb090bff3.png)
2.比如一个长列表里面嵌套了很多字典元素,我们要按照每个元素的长度大小排序
L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]
new_line=sorted(L,key=lambda x:len(x))
print(new_line)
[{1: 9}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}]
3.filter()
filter函数接受一个函数f和一个list,这个函数f的作用是对每个元素进行判断,返回True或者False,这样可以过滤掉一些不符合条件的元素,然后返回符合条件的list.
def is_even(x):
return x%2==0
print(filter(is_even,[1,2,3,4,5]))
>>>[2, 4]
特别是在处理文件的时候,需要把一些空格,回车和空字符去掉
![](https://img.haomeiwen.com/i16627003/962d38bf967a62e2.png)
def is_not_empty(str):
return str and len(str.strip()) > 0
res = filter(is_not_empty,["AAAA",None,'\n','\t',',''end','book'])
for i in res:
print(i)
參考:
链接:https://www.jianshu.com/p/63ec798b9490
网友评论