# One line of code, take you to learn Python

2022-02-02 04:34:22 jiejie

I'm learning Python In the process of , Always find out Python Can easily solve many problems .
Some complex tasks , You can even use one line Python Code will do it .
below , Small F Introduce to you 50 A very practical Python One line of code .
I hope you can find helpful skills .

## 1、 Letter heterotopic word

If two words contain the same letter , The order is different , It's called alphabetic translocation (anagram).
for example ,“silent” and “listen” It's a letter translocation , and “apple” and “aplee” It's not a translocation .

``````from collections import Counter

s1 = 'below'
s2 = 'elbow'

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

Use one line Python Code , You can tell .

## 2、 Binary to decimal

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

## 3、 Convert string to lowercase

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

print("Hi my name is XiaoF".casefold())
# 'hi my name is xiaof'
Copy code ``````

## 4、 Convert strings to uppercase

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

## 5、 Convert string to byte

``````print("convert string to bytes using encode method".encode())
# b'convert string to bytes using encode method'
Copy code ``````

## 6、 Copy files

``````import shutil

shutil.copyfile('source.txt', 'dest.txt')
Copy code ``````

## 7、 Quick sort

``````qsort = lambda l: l if len(l) <= 1 else qsort([x for x in l[1:] if x < l]) + [l] + qsort([x for x in l[1:] if x >= l])

print(qsort([17, 29, 11, 97, 103, 5]))
# [5, 11, 17, 29, 97, 103]
Copy code ``````

## 8、n The sum of consecutive numbers

``````n = 10

print(sum(range(0, n+1)))
# 55
Copy code ``````

## 9、 Exchange the values of two variables

``````a,b = b,a
Copy code ``````

## 10、 Fibonacci series

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

print(fib(20))
# 6765
Copy code ``````

## 11、 Merge nested lists into one list

``````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]
Copy code ``````

## 12、 Run one HTTP The server

``````python3 -m http.server 8000
python2 -m SimpleHTTPServer
Copy code ``````

## 13、 Reverse list

``````numbers = [0, 1, 2, 11, 12, 13, 52, 53, 54]

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

## 14、 Factorial

``````import math

fact_5 = math.factorial(5)
print(fact_5)
# 120
Copy code ``````

## 15、 Use... In list derivation for and if

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

print(even_list)
# [2, 4]
Copy code ``````

## 16、 The longest string in the list

``````words = ['This', 'is', 'a', 'list', 'of', 'words']

result = max(words, key=len)
print(result)
# 'words'
Copy code ``````

## 17、 List derivation

``````li = [num for num in range(0, 10)]

print(li)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy code ``````

## 18、 Set derivation

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

print(num_set)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Copy code ``````

## 19、 Dictionary derivation

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

print(dict_numbers)
# {1: 1, 2: 4, 3: 9, 4: 16}
Copy code ``````

## 20、if-else

``````print("even") if 4 % 2==0 else print("odd")
Copy code ``````

## 21、 Infinite loop

``````while 1:0
Copy code ``````

## 22、 Check data type

``````print(isinstance(2, int))
# True

print(isinstance("allwin", str))
# True

print(isinstance([3, 4, 1997], list))
# True
Copy code ``````

## 23、While loop

``````a = 5

while a > 0:
a = a - 1

print(a)
# 0
Copy code ``````

## 24、 Use print Statement to write to a file

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

You can print out information , It can also save information to files .

## 25、 Calculate the frequency of a character in the string

``````print("umbrella".count('l'))
# 2
Copy code ``````

## 26、 Merge list

``````list1 = [1, 2, 4]
list2 = ['XiaoF']
list1.extend(list2)

print(list1)
# [1, 2, 4, 'XiaoF']
Copy code ``````

## 27、 Merge dictionaries

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

print(dict1)
# {'name': 'weiwei', 'age': 23, 'city': 'Beijing'}
Copy code ``````

## 28、 Merge sets

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

print(set1)
# {0, 1, 2, 11, 12, 13}
Copy code ``````

## 29、 Time stamp

``````import time

print(time.time())
Copy code ``````

## 30、 The most frequent element in the list

``````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
Copy code ``````

## 31、 Nested list

``````numbers = [[num] for num in range(10)]

print(numbers)
# [, , , , , , , , , ]
Copy code ``````

## 32、 Octal to decimal

``````print(int('30', 8))
# 24
Copy code ``````

## 33、 Convert key value pairs to dictionaries

``````result = dict(name='XiaoF', age=23)

print(result)
# {'name': 'XiaoF', 'age': 23}
Copy code ``````

## 34、 Seek quotient and remainder

``````quotient, remainder = divmod(4, 5)

print(quotient, remainder)
# 0 4
Copy code ``````

divmod() The function returns when the parameter 1 Divide by parameter 2 when , Tuple containing quotient and remainder .

## 35、 Remove duplicates from the list

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

## 36、 Sort the list in ascending order

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

## 37、 Sort the list in descending order

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

## 38、 Get lowercase alphabet

``````import string

print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
Copy code ``````

## 39、 Get the upper case alphabet

``````import string

print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
Copy code ``````

## 40、 obtain 0 To 9 character string

``````import string

print(string.digits)
# 0123456789
Copy code ``````

## 41、 Hexadecimal to decimal

``````print(int('da9', 16))
# 3497
Copy code ``````

## 42、 Date time

``````import time

print(time.ctime())
# Thu Aug 13 20:00:00 2021
Copy code ``````

## 43、 Convert the string in the list to an integer

``````print(list(map(int, ['1', '2', '3'])))
# [1, 2, 3]
Copy code ``````

## 44、 Sort dictionaries with key

``````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}
Copy code ``````

## 45、 Sort dictionaries with key values

``````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)}

print(result)
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Copy code ``````

## 46、 List rotation

``````li = [1, 2, 3, 4, 5]

# li[n:] + li[:n],  Right to left
print(li[2:] + li[:2])
# [3, 4, 5, 1, 2]

# li[-n:] + li[:-n],  Left to right
print(li[-1:] + li[:-1])
# [5, 1, 2, 3, 4]
Copy code ``````

## 47、 Remove the number from the string

``````message = ''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))

print(message)
# abcdeffgvcg
Copy code ``````

## 48、 Matrix transformation

``````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]]
Copy code ``````

## 49、 List filtering

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

print(result)
# [2, 4, 6]
Copy code ``````

## 50、 Unpack

``````a, *b, c = [1, 2, 3, 4, 5]

print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5
Copy code ``````

Python It is a very diverse and well developed language , So there will certainly be many functions I didn't consider , If anyone knows , You can tell me in the comments section , You can also confide in me