25 conceptos prácticos útiles de Python que debe conocer

Esto hará que Python sea genial





Original "25 frases breves de Python útiles que debe conocer" por Abhay Parashar





Antes de leer: todo desarrollador debe tener herramientas prácticas y convenientes en sus manos. Las frases ingeniosas, como el azúcar sintáctico, son ejemplos de codificación inteligente que aumenta su productividad y calidad a los ojos de sus compañeros, pero no requiere ningún esfuerzo sobrenatural. Espero que la traducción de este artículo sea de ayuda.





, 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 necesita convertir todas las filas en columnas y viceversa, en Python puede transponer una matriz en solo una línea de código usando la función 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 las ocurrencias del patrón

Este es un método importante y de trabajo cuando necesitamos saber el número de repeticiones de un patrón en un texto. Python tiene una biblioteca re que hará el trabajo por nosotros.





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



23. Reemplazo de texto con otro texto

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



24. Lanzamiento de moneda simulado

Puede que esto no sea tan importante, pero puede ser muy útil cuando necesite generar una selección aleatoria de un conjunto de opciones dado.





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



25. Generación 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)]
      
      




He compartido todas las frases útiles e importantes que conozco. Si sabe más, comparta los comentarios.








All Articles