ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

你应该知道的 50 个 Python 单行代码

2021-10-29 19:33:52  阅读:188  来源: 互联网

标签:Python list 50 列表 单行 import print sorted li


你应该知道的 50 个 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')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2. 二进制转十进制

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

3. 转换成小写字母

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

"Hi my name is Allwin".casefold()  
# 'hi my name is allwin'
  • 1
  • 2
  • 3
  • 4
  • 5

4. 转换成大写字母

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

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

"convert string to bytes using encode method".encode()  
# b'convert string to bytes using encode method'
  • 1
  • 2

6. 复制文件

import shutil; shutil.copyfile('source.txt', 'dest.txt')
  • 1

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]])
  • 1

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
  • 1
  • 2
  • 3
  • 4
  • 5

9. 赋值交换

a,b = b,a
  • 1

10. 斐波那契数列

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

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

[item for sublist in main_list for item in sublist]
  • 1

12. 运行一个 HTTP 服务

python3 -m http.server 8000
  • 1

13. 反转列表

numbers[::-1]
  • 1

14. 求一个数的因数

import math; fact_5 = math.factorial(5)
  • 1

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

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

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

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

17. 列表推导式

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

18. 集合推导式

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

19. 字典推导式

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

20. if-else

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

21. 无限循环

while 1:0
  • 1

22. 检查数据类型

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

23. While 循环

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

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

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

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

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

26. 合并两个列表

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

27. 合并两个字典

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

28. 合并两个集合

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

29. 时间戳

import time; print(time.time())
  • 1

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

31. 嵌套的列表推导式

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

32. 八进制转十进制

print(int('30', 8))   
# 24
  • 1
  • 2

33. 将键值对转换为字典

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

34. 计算商和余数

quotient, remainder = divmod(4,5)
  • 1

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

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

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

37. 对列表进行降序排序

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

38. 获取一串小写字母

import string; print(string.ascii_lowercase)  
# abcdefghijklmnopqrstuvwxyz
  • 1
  • 2

39. 获取一串大写字母

import string; print(string.ascii_uppercase)  
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • 1
  • 2

40. 获取字符串类型的0到9的数字

import string; print(string.digits)  
# 0123456789
  • 1
  • 2

41. 十六进制转十进制

print(int('da9', 16))  
# 3497
  • 1
  • 2

42. 人类可读的日期时间

import time; print(time.ctime())  
# Thu Aug 13 20:16:23 2020
  • 1
  • 2

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

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

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}
  • 1
  • 2
  • 3

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}
  • 1
  • 2
  • 3

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

47. 从字符串中删除数字

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

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]]
  • 1
  • 2
  • 3

49. 从列表中过滤偶数

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

50. 解包操作

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

来自:https://blog.csdn.net/os373/article/details/121035063?spm=1000.2115.3001.5927#8_n__48

标签:Python,list,50,列表,单行,import,print,sorted,li
来源: https://www.cnblogs.com/BetterThanEver_Victor/p/15481968.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有