美文网首页
Python若干小技巧(1)

Python若干小技巧(1)

作者: 大兔子先生 | 来源:发表于2017-04-17 11:17 被阅读0次

原地交换两个变量

x,y=10,20
print x,y

x,y=y,x
print x,y

#output
10 20
20 10

赋值号“=”的右侧构成一个新的元组(tuple),左侧立即解析(unpack)那个(未被引用的)元组到变量a和b。赋值完成之后,由于元组(20,10)未被引用,根据引用计数(reference counting)的垃圾回收(garbage collection)机制,该元组作为垃圾被回收。

链式比较运算符

n=10
print 1<n<20
print 1<n<5
print 10<20<20<30

#output
True
False
False

链式比较操作符,中间只要有“一环”为False,则返回False。

使用if-else进行条件赋值

[1 if x>4 else -1 for x in range(10)]

#output
[-1, -1, -1, -1, -1, 1, 1, 1, 1, 1]

也可以嵌套使用

def minimum(a,b,c):
    return a if a<=b and a<=c else (b if b<=a and b<=c else c)

print maximum(15,10,30)

#output
10

打印module的文件路径

import socket
print socket

#output
<module 'socket' from '/usr/lib/python2.7/socket.pyc'>

查看Python对象的方法

可以用dir()方法来检查Python对象的方法

test=[1,2,3]
print dir(test)

#output
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__','__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

相关文章

网友评论

      本文标题:Python若干小技巧(1)

      本文链接:https://www.haomeiwen.com/subject/exazattx.html