一行Python代码能做哪些不可思议的骚操作?

使用 Python 总是可以轻松完成一些特定任务,这让人惊奇。一些比较繁琐的任务可以使用 Python 在单行代码中完成。下面是我收集的 50 个 Python 单行代码实例。

1. 字母移位词:猜字母的个数和频次是否相同

from collections import Counter  

s1 = 'below'  
s2 = 'elbow'  

print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')

or we can also do this using the sorted() method like this.

print('anagram') if sorted(s1) == sorted(s2) else print('not an anagram')

2.二进制转十进制

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

3. 转换成小写字母

"Hi my name is Allwin".lower() 
# 'hi my name is allwin'  

"Hi my name is Allwin".casefold()  
# 'hi my name is allwin'

4. 转换成大写字母

"hi my name is Allwin".upper()  
# 'HI MY NAME IS ALLWIN'

5. 字符串转换为字节类型

"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]])

8. n 个连续数之和

sum(range(0, n+1))

This is not efficient and we can do the same using the below formula.

sum_n = n*(n+1)//2

9. 赋值交换

a,b = b,a

10. 菲波那切数列

fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2)  # 正确的菲波那切数列函数菲波那切数列函数菲波那切数列函数
fib(8) # 结果应该是21

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

[item for sublist in main_list for item in sublist]

12. 运行一个 HTTP 服务

python3 -m http.server 8000

13. 反转列表

numbers[::-1]

14. 求一个数的因数

import math; fact_5 = math.factorial(5)

15. 使用“for”和“if”的列表解析

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

16. 从列表中得到最长的字符串

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

17. 列表推导式

li = [num for num in range(0,100)]  
# this will create a list of numbers from 0 to 99

18. 集合推导式

num_set = { num for num in range(0,100)}  
# this will create a set of numbers from 0 to 99

19. 字典推导式

dict_numbers = {x:x*x for x in range(1,5) }  
# {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. 检查数据类型

isinstance(2, int)  
isinstance("allwin", str)  
isinstance([3,4,1997], list)

23. While 循环

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

24. 使用“print()”写入文件

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

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

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

26. 合并两个列表

list1.extend(list2)# contents of list 2 will be added to the list1

27. 合并两个字典

dict1.update(dict2)  
# contents of dictionary 2 will be added to the dictionary 1

28. 合并两个集合

set1.update(set2)  
# contents of set2 will be copied to the set1

29. 时间戳

import time; print(time.time())

30. 出现次数最多的元素

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

However, this is not efficient and we can do the same using the collections module in a more efficient way like this.

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  

from collections import Counter  
print(Counter(numbers).most_common()[0][0])# 4

31. 嵌套的列表推导式

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

32. 八进制转十进制

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

33. 将键值对转换为字典

dict(name='allwin', age=23)

34. 计算商和余数

quotient, remainder = divmod(4,5)

35. 从列表中删除重复元素

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

36. 对列表进行升序排序

First, let us sort the list using the sorted() method. The sorted method will **return the sorted list**.

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

Next, let us sort this using the sort() method. The sort() method will sort the original list and not return anything.

li = [5, 2, 9, 1]  
li.sort()  

print(li)  
# 1, 2, 5, 9

37. 对列表进行降序排序

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:16:23 2020

43. 将列表元素的字符串类型转换为整型

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

44. 按"键"对字典进行排序

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

45. 按"值"对字典进行排序

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

46. 旋转列表

# li = [1,2,3,4,5]# right to left  
li[n:] + li[:n] # n is the no of rotations  
li[2:] + li[:2]  
[3, 4, 5, 1, 2]# left to right  
li[-n:] + li[:-n]  
li[-1:] + li[:-1]   
[5, 1, 2, 3, 4]

47. 从字符串中删除数字

''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))  
# abcdeffgvcg

48. 转置矩阵

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

49. 从列表中过滤偶数

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

50. 解包操作

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

 最后祝大家天天进步!!学习Python最重要的就是心态。我们在学习过程中必然会遇到很多难题,可能自己想破脑袋都无法解决。这都是正常的,千万别急着否定自己,怀疑自己。如果大家在刚开始学习中遇到困难,想找一个python学习交流环境,可以加入我们的python裙,领取学习资料,一起讨论,会节约很多时间,减少很多遇到的难题。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值