分享50条经典的Python一行代码

嵌入式技术

1330人已加入

描述

前言

大家好,这里是浩道Linux,主要给大家分享Linux、Python、网络通信、网络安全等相关的IT知识平台。

今天浩道跟大家分享python学习过程中非常经典的50条一行代码,让大家体验它简洁而功能强大的特点。

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')

 

上面代码运行结果:

anagram

2.二进制转十进制

 

decimal = int('1010101010', 2)
print(decimal)

 

上面代码运行结果:

682

3.将字符串转换为小写

 

print("Hi,my name is IMOONrong".lower())
print("Hi,my name is IMOONrong".casefold())

 

上面代码运行结果:

hi,my name is imoonrong

hi,my name is imoonrong

4.将字符串转换为大写

 

print("Hi,my name is IMOONrong".upper())

 

上面代码运行结果:

HI,MY NAME IS IMOONRONG

5.将字符串转换为字节

 

print("convert string to bytes using encode method".encode())

 

上面代码运行结果:

b'convert string to bytes using encode method'

6.拷贝文件

 

import shutil


shutil.copyfile('myfile01.xlsx', 'myfile02.xlsx')

 

上面代码运行后,在相同目录下复制得到myfile02.xlsx文件。

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([117,19,181,907,26,9999,73,2023]))

 

上面代码运行结果:

[19, 26, 73, 117, 181, 907, 2023, 9999]

8.n个连续数求和

 

n = 100

print(sum(range(0, n+1)))

 

上面代码运行结果:

5050

9.交换两个变量的值

 

a,b=b,a

比如,输入下面值查看结果:
a=100
b=200
a,b=b,a
print(a,b)
输出:200 100

 

10.斐波纳契数列

斐波那契数列(Fibonacci sequence)是一个无限数列,它以0和1作为前两项,后面每一项都是前两项的和。即:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, ...

斐波那契数列最早是由数学家斐波那契在13世纪提出的,它在数学、计算机科学、自然科学等领域都有广泛的应用。例如,斐波那契数列可以用于解决一些动态规划问题、编写高效的算法和数据结构、分析金融市场、研究植物的生长规律等。

斐波那契数列的通项公式为:Fn = (1/sqrt(5)) * (((1+sqrt(5))/2)^n - ((1-sqrt(5))/2)^n),其中n表示斐波那契数列的第n项,^表示幂运算,sqrt表示开方运算。

 

fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2)

print(fib(11))

 

上面代码运行结果:

89

可以看出输出结果为上面所列,除0的第11位,即89。

11.将嵌套列表合并为一个列表

 

main_list = [[0, 9, 2], [11, 162, 13], [52, 593, 162]]

result = [item for sublist in main_list for item in sublist]
print(result)

 

上面代码运行结果:

[0, 9, 2, 11, 162, 13, 52, 593, 162]

12.运行一个HTTP服务器

 

python -m http.server:8000

 

![image-20230616160933306](50 条有趣的 Python 一行代码.assets/image-20230616160933306.png)

访问资源:

![image-20230616161026462](50 条有趣的 Python 一行代码.assets/image-20230616161026462.png)

13.反转列表

 

numbers = [9, 111, 7, 15, 11, 17, 52, 59, 177]

print(numbers[::-1])

 

上面代码运行结果:

[177, 59, 52, 17, 11, 15, 7, 111, 9]

14.阶乘

 

import math

jc_100 = math.factorial(100)
print(jc_100)

 

上面代码运行结果:

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

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

 

even_list = [number for number in [21, 12, 63, 84] if number % 2 == 0]

print(even_list)

 

上面代码运行结果:

[12, 84]

16.列表中最长的字符串

 

mywords = ['Take', 'control', 'of', 'your', 'own', 'desting']
#命运掌握在自己手上

result = max(mywords, key=len)
print(result)

 

上面代码运行结果:

control

17.列表推导式

 

mylist = [num for num in range(0, 20)]

print(mylist)

 

上面代码运行结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

18.集合推导式

 

num_set = {num for num in range(0, 20)}

print(num_set)

 

上面代码运行结果:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}

19.字典推导式

 

dict_numbers = {x: x*x for x in range(1, 10)}

print(dict_numbers)

 

上面代码运行结果:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

20.if-else

 

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

 

上面代码运行结果:

even

21.无限循环

 

while 1:0

 

执行上面语句,一直处理运行状态。

22.检查数据类型

 

print(isinstance(2.0, int))
print(isinstance("allwin", str))
print(isinstance([2023, 1997], list))

 

执行上面3条语句后,输出:

False

True

True

23.While循环

 

a = 50

while a > 0:
    a = a - 1

print(a)

 

上面代码运行结果:

0

24.使用print语句写入文件

 

print("Hello, World!", file=open('file.txt', 'w'))

 

执行上面语句后,在当前文件夹下生成file.txt文件,并且文件内容为Hello, World!。

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

 

print("Congratulations".count('o'))

 

上面代码运行结果:

2

26.合并列表

 

list1 = [2, 5, 8, 90]
list2 = ['teacher']
list1.extend(list2)

print(list1)

 

上面代码运行结果:

[2, 5, 8, 90, 'teacher']

27.合并字典

 

dict1 = {'name': 'qiyou', 'age': 4}
dict2 = {'city': 'HebQhd'}
dict1.update(dict2)

print(dict1)

 

上面代码运行结果:

{'name': 'qiyou', 'age': 4, 'city': 'HebQhd'}

28.合并集合

 

set1 = {9, 66, 789}
set2 = {89, 90, 911}
set1.update(set2)

print(set1)

 

上面代码运行结果:

{89, 66, 789, 9, 90, 911}

29.时间戳

 

import time

print(time.time())

 

上面代码运行结果:

1686906036.2873256

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

 

my_list = [90, 6, 12, 6, 6, 6, 77, 87, 6]
most_frequent_element = max(set(my_list), key=my_list.count)

print(most_frequent_element)

 

上面代码运行结果:

6

31.嵌套列表

 

numbers = [[num] for num in range(20)]

print(numbers)

 

上面代码运行结果:

[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]]

32.八进制转十进制

 

print(int('30', 8)) 

 

上面代码运行结果:

24

33.将键值对转换为字典

 

myresult = dict(name='qiyou', age=4)

print(myresult)

 

上面代码运行结果:

{'name': 'qiyou', 'age': 4}

34.求商和余数

 

quotient, remainder = divmod(196, 7)

print(quotient, remainder)

 

上面代码运行结果:

28 0

35.删除列表中的重复项

 

print(list(set([100, 100, 90, 100, 200])))

 

上面代码运行结果:

[200, 90, 100]

36.按升序排序列表

 

print(sorted([97, 12, 109, 63]))

 

上面代码运行结果:

[12, 63, 97, 109]

37.按降序排序列表

 

print(sorted([97, 12, 109, 63],reverse=True))

 

上面代码运行结果:

[109, 97, 63, 12]

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('ABCDE0', 16))

 

上面代码运行结果:

11259360

42.日期时间

 

import time

print(time.ctime())

 

上面代码运行结果:

Fri Jun 16 1745 2023

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

 

print(list(map(int, ['9', '5', '6'])))

 

上面代码运行结果:

[9, 5, 6]

44.用键对字典进行排序

 

d = {'one': 1, 'five': 5, 'eight': 8}
result = {key: d[key] for key in sorted(d.keys())}

print(result)

 

上面代码运行结果:

{'eight': 8, 'five': 5, 'one': 1}

45.用键值对字典进行排序

 

x = {'two': 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, 'two': 2, 4: 3, 3: 4}

46.列表旋转

 

li = [10, 'd', 'f', 6, 5]

# li[n:] + li[:n], 右变左
print(li[2:] + li[:2])


# li[-n:] + li[:-n], 左变右
print(li[-1:] + li[:-1])

 

上面代码运行结果:

['f', 6, 5, 10, 'd']

[5, 10, 'd', 'f', 6]

47.将字符串中的数字移除

 

mymessage = ''.join(list(filter(lambda x: x.isalpha(), 'def987bc123def443hj77')))

print(mymessage)

 

上面代码运行结果:

defbcdefhj

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, 6]

print(a) 
print(b) 
print(c)

 

上面代码运行结果:

1

[2, 3, 4, 5]

6

 

  审核编辑:汤梓红
 
打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分