25 One-Liners úteis do Python que você deve conhecer

Isso tornará o Python ótimo





Original "25 One-Liners Úteis de Python que Você Deve Saber" por Abhay Parashar





Antes de ler: todo desenvolvedor deve ter ferramentas convenientes e práticas em suas mãos. One-liners, como o açúcar sintático, são exemplos de codificação inteligente que aumenta sua produtividade e qualidade aos olhos de seus colegas, mas não requer nenhum esforço sobrenatural. Espero que a tradução deste artigo seja útil.





, 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.

Se você precisar converter todas as linhas em colunas e vice-versa, em python você pode transpor uma matriz em apenas uma linha de código usando a função 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. Contando as ocorrências do padrão

Este é um método importante e útil quando precisamos saber o número de repetições de um padrão em um texto. Python tem uma nova biblioteca que fará o trabalho para nós.





import re; len(re.findall('python','python is a programming language. python is python.'))
> 3
      
      



23. Substituindo o texto por outro texto

"python is a programming language. python is python".replace("python",'Java')
> Java is a programming language. Java is Java
      
      



24. Simulado sorteio

Isso pode não ser tão importante, mas pode ser muito útil quando você precisa gerar uma seleção aleatória de um determinado conjunto de opções.





import random; random.choice(['Head',"Tail"])
> Head
      
      



25. Geração de grupos

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




Compartilhei todas as frases simples e úteis que conheço. Se você souber de mais alguma coisa, compartilhe nos comentários.








All Articles