python的一些有趣的小知识三

114 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情

"Gawky and proud of it."

"On the Internet, nobody knows you're a dog."

今天就再继续给大家来介绍一些python相关的有趣和使用的小技巧吧,感兴趣的赶紧关注起来哦

对列表中的元素(字典)进行排序

如果一提到排序两个字的话,我们一般会立马想到sort或者sorted,两者用法如下:

sorted函数二十对可迭代对象进行排序,但是不修改源对象,会返回一个新的值

x=[8,9,0,7,4,5,1,2,3,6]
x.sort(key,reverse=True)
复制代码

sorted()函数会返回一个排序列表,不改变原有序列**

 x=[8,9,0,7,4,5,1,2,3,6]
 y=sorted(x,key,reverse=True)
复制代码

当我们有需求需要对list中的元素进行排序,且元素是字典,且排序的key可能为空或者不存在时候就会出现这个错:TypeError: '<' not supported between instances of 'NoneType' and 'int',这是因为取值的时候我们的这个key不是int,这个在python2中可能是不会存在的,因为python2中的None等同于0,解决办法也很简单, 只需要一个我个人非常喜欢的三元表达式即可。x.get["a"] if x.get("a") else 65535),详细代码如下:

a = [{"a": 1}, {"a": None}]

print(sorted(a, key=lambda x:x.get["a"]if x.get("a") else 65535))
# a.sort(key=lambda x: x.get["a"] if x.get("a") else 65535)
复制代码

不仅是转义字符还是换行符

# 多行字符串

multistr = "select * from multi_row \
where row_id < 5"
print(multistr)
复制代码

print('模块名') # 可以打印出模块的绝对路劲,前提是导入该模块

import sys
if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):
    print("sorry, you are not running on python 2.7")
    print("current python version:", sys.version)
复制代码

dir(模块名或者对象) # 可以打印出模块或对象中使用的方法

# 检查python中的对象
test = [1, 3, 5, 7]
print(dir(test))
test = range(10)
print(dir(test))
复制代码

把列表元组中多个字符串添加在字符串中的方法"".join(test)) #test为列表元组字典对象

# 组合多个字符串
test = ["I", "Like", "Python"]
print(test)
print("".join(test))


作者:rational
链接:juejin.cn/post/708907… 来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。