Cela rendra Python génial
"25 One-Liners Python utiles que vous devriez connaître" par Abhay Parashar
Avant de lire: chaque développeur doit avoir entre les mains des outils pratiques et pratiques. Les one-liners, comme le sucre syntaxique, sont des exemples de codage intelligent qui augmente votre productivité et votre qualité aux yeux de vos pairs, mais ne nécessite aucun effort surnaturel. J'espère que la traduction de cet article vous sera utile.
, Python, , . Python.
1.
# a = 4 b = 5
a,b = b,a
# print(a,b) >> 5,4
- , , . - , .
2.
a,b,c = 4,5.5,'Hello'
#print(a,b,c) >> 4,5.5,hello
, . , var . . .
a,b,*c = [1,2,3,4,5]
print(a,b,c)
> 1 2 [3,4,5]
3.
, - .
a = [1,2,3,4,5,6]
s = sum([num for num in a if num%2 == 0])
print(s)
>> 12
4.
del
- , Python .
####
a = [1,2,3,4,5]
del a[1::2]
print(a)
>[1, 3, 5]
5.
lst = [line.strip() for line in open('data.txt')]
print(lst)
, . for
. strip
. , .
list(open('data.txt'))
## with
with open("data.txt") as f: lst=[line.strip() for line in f]
print(lst)
6.
with open("data.txt",'a',newline='\n') as f: f.write("Python is awesome")
data.txt, , Python is awesome
.
7.
lst = [i for i in range(0,10)]
print(lst)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = list(range(0,10))
print(lst)
, .
lst = [("Hello "+i) for i in ['Karl','Abhay','Zen']]
print(lst)
> ['Hello Karl', 'Hello Abhay', 'Hello Zen']
8. Mapping ,
. , , - , , . Python. map
, .
list(map(int,['1','2','3']))
> [1, 2, 3]
list(map(float,[1,2,3]))
> [1.0, 2.0, 3.0]
#
[float(i) for i in [1,2,3]]
> [1.0, 2.0, 3.0]
9.
, , . , .
#
{x**2 for x in range(10) if x%2==0}
> {0, 4, 16, 36, 64}
10. Fizz Buzz
, , 1 100. , , «Fizz» , «Buzz». ( , , , , FizzBuzz).
, if-else. , , , 10 . python, FizzBuzz .
['FizzBuzz' if i%3==0 and i%5==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i for i in range(1,20)]
1 20, , 3 5. , Fizz Buzz ( FizzBuzz).
11.
- , .
text = 'level'
ispalindrome = text == text[::-1]
ispalindrome
> True
12. , ,
lis = list(map(int, input().split()))
print(lis)
> 1 2 3 4 5 6 7 8
[1, 2, 3, 4, 5, 6, 7, 8]
13. -
- - .
- , __.
sqr = lambda x: x * x ##,
sqr(10)
> 100
14.
num = 5
if num in [1,2,3,4,5]:
print('present')
> present
15.
- , . python , .
n = 5
print('\n'.join('?' * i for i in range(1, n + 1)))
>
?
??
???
????
?????
16.
- .
import math
n = 6
math.factorial(n)
> 720
17.
- , ( ) . : 1, 1, 2, 3, 5, 8, 13 .. for .
fibo = [0,1]
[fibo.append(fibo[-2]+fibo[-1]) for i in range(5)]
fibo
> [0, 1, 1, 2, 3, 5, 8]
18.
- , 1. : 2,3,5,7 . . , .
list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13)))
> [2, 3, 5, 7, 11]
19.
findmax = lambda x,y: x if x > y else y
findmax(5,14)
> 14
max(5,14)
- .
20.
2 5 . , .
def scale(lst, x): return [i*x for i in lst]
scale([2,3,4], 2) ##
> [4,6,8]
21.
Si vous avez besoin de convertir toutes les lignes en colonnes et vice versa, en python, vous pouvez transposer une matrice en une seule ligne de code à l'aide de la fonction zip.
a=[[1,2,3],
[4,5,6],
[7,8,9]]
transpose = [list(i) for i in zip(*a)]
transpose
> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
22. Comptage des occurrences du motif
Il s'agit d'une méthode importante et fonctionnelle lorsque nous avons besoin de connaître le nombre de répétitions d'un motif dans un texte. Python a une bibliothèque re qui fera le travail pour nous.
import re; len(re.findall('python','python is a programming language. python is python.'))
> 3
23. Remplacement du texte par un autre texte
"python is a programming language. python is python".replace("python",'Java')
> Java is a programming language. Java is Java
24. Tirage au sort simulé
Cela peut ne pas être si important, mais cela peut être très utile lorsque vous devez générer une sélection aléatoire à partir d'un ensemble d'options donné.
import random; random.choice(['Head',"Tail"])
> Head
25. Génération de groupes
groups = [(a, b) for a in ['a', 'b'] for b in [1, 2, 3]]
groups
> [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
J'ai partagé tous les one-liners utiles et importants que je connais. Si vous en savez plus, partagez dans les commentaires.