python Oneline code,And和Or的妙用

简单的If和Else:

1
2
3
4
5
6
7
8
9
10
11
12
13
a = 4

if a > 3:
if a > 4:
j = ">4"
else:
j = "3< <=4"
else:
j = "<=3"

# there are the same.
print(j)
print(a>3 and (a>4 and ">4" or "3< <=4") or "<=3")

这个If语句和下面的Or and 是一样的结果。

启动线程并同时保存到列表中

常规版:

1
2
3
4
5
threadList = []
for i in range(5):
newThread = threading.Thread(target=want)
threadList.append(newThread)
newThread.start()

One-line code:

1
threadList = [t.start() or t for i in range(5) for t in [threading.Thread(target=want)]]