在学习Python的过程中,你总会发现Python可以轻松解决很多问题。一些复杂的任务甚至可以用一行 Python 代码完成。
这里有25个有趣的Python代码,个个都很实用。我希望你能发现它们很有用。
如果两个单词包含相同的字母并且顺序不同,则它们被称为变位词。例如,“silent”和“listen”是字母变位词,而“apple”和“aplee”则不是。
from collections import Counter s1 = 'below' s2 = 'elbow' print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')
decimal = int('1010', 2) print(decimal) #10
print('Hi my name is Jack Chen'.lower())# 'hi my name is Jack Chen'print('Hi my name is Jack Chen'.casefold())# 'hi my name is Jack Chen'
print('hi my name is Jack Chen'.upper()) # 'HI MY NAME IS Jack Chen'
print('convert string to bytes using encode method'.encode()) # b'convert string to bytes using encode method'
import shutil shutil.copyfile('source.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在 l[1:] if x >= l[0]]) print(qsort([17, 29, 11, 97, 103, 5])) # [5, 11, 17, 29, 97, 103]
n = 10打印((λ x: (x*(x+1))/2)(n) # 55
a, b = b, a
fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2) print(fib(20)) # 6765
main_list = [[0, 1, 2], [11, 12, 13], [52, 53, 54]]result = [item for sublist in main_list for item in sublist]print(result)# [0, 1, 2, 11, 12, 13, 52, 53, 54]
python3 -m http.server 8000 python2 -m SimpleHTTPServer
numbers = [0, 1, 2, 11, 12, 13, 52, 53, 54] print(numbers[::-1]) # [54, 53, 52, 13, 12, 11, 2, 1, 0 ]
import mathfact_5 = math.factorial(5) print(fact_5) # 120
even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0] print(even_list) # [2, 4]
words = ['This’, 'is’, 'a’, 'list’, 'of’, 'words’] result = max(words, key=len) print(result) # 'words’
li = [num for num in range(0, 10)] print(li) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
num_set = {num for num in range(0, 10)} print(num_set) # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
dict_numbers = {x: x*x for x in range(1, 5)} print(dict_numbers) # {1: 1, 2: 4, 3: 9, 4: 16}
print('even') if 4 % 2==0 else print('odd')
while 1:0
print(isinstance(2, int)) # True print(isinstance('allwin', str)) # True print(isinstance([3, 4, 1997], list)) # True
print('Hello, World!', file=open('file.txt', 'w'))
print('umbrella'.count('l'))# 2
如果你发现我的任何文章对你有帮助或者有用,麻烦点赞或者转发。 谢谢!
联系客服