Python 50条有趣的Python一行代码

▍1、字母异位词

两个单词如果包含相同的字母,次序不同,则称为字母易位词(anagram)。
例如,“silent”和“listen”是字母易位词,而“apple”和“aplee”不是易位词。
from collections import Counter
s1 = \'below\'
s2 = \'elbow\'
print(\'anagram\') if Counter(s1) == Counter(s2) else print(\'not an anagram\')
使用一行Python代码,就能判断出来了。

▍2、二进制转十进制

decimal = int(\'1010\', 2)
print(decimal) #10

▍3、将字符串转换为小写

print(\"Hi my name is XiaoF\".lower())
# \'hi my name is xiaof\'
print(\"Hi my name is XiaoF\".casefold())
# \'hi my name is xiaof\'

▍4、将字符串转换为大写

print(\"hi my name is XiaoF\".upper())
# \'HI MY NAME IS XIAOF\'

▍5、将字符串转换为字节

print(\"convert string to bytes using encode method\".encode())
# b\'convert string to bytes using encode method\'

▍6、拷贝文件

import shutil
shutil.copyfile(\'source.txt\', \'dest.txt\')

▍7、快速排序

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]])
print(qsort([17, 29, 11, 97, 103, 5]))
# [5, 11, 17, 29, 97, 103]

▍8、n个连续数的和

n = 10
print(sum(range(0, n+1)))
# 55

▍9、交换两个变量的值

a,b = b,a

▍10、斐波纳契数列

fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2)
print(fib(20))
# 6765

▍11、将嵌套列表合并为一个列表

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]

▍12、运行一个HTTP服务器

python3 -m http.server 8000
python2 -m SimpleHTTPServer

▍13、反转列表

numbers = [0, 1, 2, 11, 12, 13, 52, 53, 54]
print(numbers[::-1])
# [54, 53, 52, 13, 12, 11, 2, 1, 0]

▍14、阶乘

import math
fact_5 = math.factorial(5)
print(fact_5)
# 120

▍15、在列表推导式中使用for和if

even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
print(even_list)
# [2, 4]

▍16、列表中最长的字符串

words = [\'This\', \'is\', \'a\', \'list\', \'of\', \'words\']
result = max(words, key=len)
print(result)
# \'words\'

▍17、列表推导式

li = [num for num in range(0, 10)]
print(li)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

▍18、集合推导式

num_set = {num for num in range(0, 10)}
print(num_set)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

▍19、字典推导式

dict_numbers = {x: x*x for x in range(1, 5)}
print(dict_numbers)
# {1: 1, 2: 4, 3: 9, 4: 16}

▍20、if-else

print(\"even\") if 4 % 2==0 else print(\"odd\")

▍21、无限循环

while 1:0

▍22、检查数据类型

print(isinstance(2, int))
# True
print(isinstance(\"allwin\", str))
# True
print(isinstance([3, 4, 1997], list))
# True

▍23、While循环

a = 5
while a > 0:
    a = a - 1
print(a)
# 0

▍24、使用print语句写入文件

print(\"Hello, World!\", file=open(\'file.txt\', \'w\'))
既可打印出信息,还能将信息保存文件。

▍25、计算一个字符在字符串中出现的频率

print(\"umbrella\".count(\'l\'))
# 2

▍26、合并列表

list1 = [1, 2, 4]
list2 = [\'XiaoF\']
list1.extend(list2)
print(list1)
# [1, 2, 4, \'XiaoF\']

▍27、合并字典

dict1 = {\'name\': \'weiwei\', \'age\': 23}
dict2 = {\'city\': \'Beijing\'}
dict1.update(dict2)
print(dict1)
# {\'name\': \'weiwei\', \'age\': 23, \'city\': \'Beijing\'}

▍28、合并集合

set1 = {0, 1, 2}
set2 = {11, 12, 13}
set1.update(set2)
print(set1)
# {0, 1, 2, 11, 12, 13}

▍29、时间戳

import time
print(time.time())

▍30、列表中出现次数最多的元素

test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4]
most_frequent_element = max(set(test_list), key=test_list.count)
print(most_frequent_element)
# 4

▍31、嵌套列表

numbers = [[num] for num in range(10)]
print(numbers)
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]

▍32、八进制转十进制

print(int(\'30\', 8))
# 24

▍33、将键值对转换为字典

result = dict(name=\'XiaoF\', age=23)
print(result)
# {\'name\': \'XiaoF\', \'age\': 23}

▍34、求商和余数

quotient, remainder = divmod(4, 5)
print(quotient, remainder)
# 0 4
divmod()函数返回当参数1除以参数2时,包含商和余数的元组。

▍35、删除列表中的重复项

print(list(set([4, 4, 5, 5, 6])))
# [4, 5, 6]

▍36、按升序排序列表

print(sorted([5, 2, 9, 1]))
# [1, 2, 5, 9]

▍37、按降序排序列表

print(sorted([5, 2, 9, 1], reverse=True))
# [9, 5, 2, 1]

▍38、获取小写字母表

import string
print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz

▍39、获取大写字母表

import string
print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ

▍40、获取0到9字符串

import string
print(string.digits)
# 0123456789

▍41、十六进制转十进制

print(int(\'da9\', 16))
# 3497

▍42、日期时间

import time
print(time.ctime())
# Thu Aug 13 20:00:00 2021

▍43、将列表中的字符串转换为整数

print(list(map(int, [\'1\', \'2\', \'3\'])))
# [1, 2, 3]

▍44、用键对字典进行排序

d = {\'one\': 1, \'four\': 4, \'eight\': 8}
result = {key: d[key] for key in sorted(d.keys())}
print(result)
# {\'eight\': 8, \'four\': 4, \'one\': 1}

▍45、用键值对字典进行排序

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
result = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(result)
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

▍46、列表旋转

li = [1, 2, 3, 4, 5]
# li[n:] + li[:n], 右变左
print(li[2:] + li[:2])
# [3, 4, 5, 1, 2]
# li[-n:] + li[:-n], 左变右
print(li[-1:] + li[:-1])
# [5, 1, 2, 3, 4]

▍47、将字符串中的数字移除

message = \'\'.join(list(filter(lambda x: x.isalpha(), \'abc123def4fg56vcg2\')))
print(message)
# abcdeffgvcg

▍48、矩阵变换

old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]
result = list(list(x) for x in zip(*old_list))
print(result)
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]

▍49、列表过滤

result = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))
print(result)
# [2, 4, 6]

▍50、解包

a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5

本文来自一日成建站教程https://www.yiricheng.cn/),为广大编程爱好者提供零基础快速搭建博客网站的方法,分享计算机网络、HTML、CSS,、JavaScript、PHP、响应式设计以及Python自动化办公的博客文章,各类小工具、电子书、免费教程。