What can Python do with one line of code, 30 practical case codes explained

Python syntax is concise, and it can achieve many interesting functions with one line of code. This time, we will organize 30 common Python one-line code collections.

1. Transpose the matrix

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

2, binary to decimal

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

3. String uppercase to lowercase

# 方法一 lower()
"Hi my name is Allwin".lower()
# 'hi my name is allwin'
# 方法二 casefold()
"Hi my name is Allwin".casefold()
# 'hi my name is allwin'
'hi my name is allwin'

4. String lowercase to uppercase

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

5. Convert string to bytes

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

6. Copy the contents of the file

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

7. Quick Sort

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]])
qsort([1,3,2])
[1, 2, 3]

8. The sum of n consecutive numbers

n = 3
sum(range(0, n+1))
6

9. Swap two variables

a=1
b=2
a,b = b,a

10. Fibonacci sequence

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

11. Combine nested lists into one list

main_list = [[1,2],[3,4],[5,6,7]]
[item for sublist in main_list for item in sublist]
[1, 2, 3, 4, 5, 6, 7]

12. Run the HTTP server

python3 -m http.server 8000

13. Reverse the list

numbers = 'I Love China'
numbers[::-1]
'anihC evoL I'

14. Return factorial

import math; fact_5 = math.factorial(5)
fact_5
120

15. Judgment list comprehension

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

16. Take the longest string

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

17. List Comprehension

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

18. Set comprehension

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

19. Dictionary comprehension

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

21. Infinite loop

while 1:0

22. Check the data type

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

23, while loop

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

24. Use the print statement to write to the file

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

25. Statistical word frequency

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

26. Merge two lists

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

27. Merge two dictionaries

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

28. Merge two sets

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

29. Timestamp

import time; print(time.time())
1632146103.8406303

30. Elements with the most statistics

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

Finally, the Python code philosophy advocates simplicity, and partners can also try to simplify the code to see if they can achieve the desired functions.

Guess you like

Origin blog.csdn.net/BYGFJ/article/details/123932569