Python语法简洁,能够用一行代码实现很多有趣的功能,这次来整理30个常见的Python一行代码集合。
old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]
list(list(x) for x in zip(*old_list))
[[1, 3, 5], [2, 4, 6], [3, 6, 7]]
decimal = int('1010', 2)
print(decimal) #10
10
# 方法一 lower()
"Hi my name is Allwin".lower()
# 'hi my name is allwin'
# 方法二 casefold()
"Hi my name is Allwin".casefold()
# 'hi my name is allwin'
'hi my name is allwin'
"hi my name is Allwin".upper()
# 'HI MY NAME IS ALLWIN'
'HI MY NAME IS ALLWIN'
"convert string to bytes using encode method".encode()
# b'convert string to bytes using encode method'
b'convert string to bytes using encode method'
import shutil; shutil.copyfile('source.txt', 'dest.txt')
'dest.txt'
qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])
qsort([1,3,2])
[1, 2, 3]
n = 3
sum(range(0, n+1))
6
a=1
b=2
a,b = b,a
fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2)
fib(10)
55
main_list = [[1,2],[3,4],[5,6,7]]
[item for sublist in main_list for item in sublist]
[1, 2, 3, 4, 5, 6, 7]
python3 -m http.server 8000
numbers = 'I Love China'
numbers[::-1]
'anihC evoL I'
import math; fact_5 = math.factorial(5)
fact_5
120
even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
even_list
[2, 4]
words = ['This', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
'words'
li = [num for num in range(0,100)]
# this will create a list of numbers from 0 to 99
num_set = { num for num in range(0,100)}
# this will create a set of numbers from 0 to 99
dict_numbers = {x:x*x for x in range(1,5) }
# {1: 1, 2: 4, 3: 9, 4: 16}
print("even") if 4%2==0 else print("odd")
even
while 1:0
isinstance(2, int)
isinstance("allwin", str)
isinstance([3,4,1997], list)
a=5
while a > 0: a = a - 1; print(a)
print("Hello, World!", file=open('source.txt', 'w'))
print("umbrella".count('l'))
2
list1.extend(list2)
# contents of list 2 will be added to the list1
dict1.update(dict2)
# contents of dictionary 2 will be added to the dictionary 1
set1.update(set2)
# contents of set2 will be copied to the set1
import time; print(time.time())
1632146103.8406303
test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4]
most_frequent_element = max(set(test_list), key=test_list.count)
most_frequent_element
4
最后,Python代码哲学崇尚简洁,伙伴们也可以尝试把代码简化,看能不能实现想要的功能。
本文参考medium文章:
https://allwin-raju-12.medium.com/50-python-one-liners-everyone-should-know-182ea7c8de9d
●关于 AB Test 你要知道的一切
●10大Python数据可视化库!