¿Cuáles son algunos trucos geniales de Python?

1. Servidor de alojamiento de archivos de un solo comando:

python -m http.server

toma cualquier valor entero entre 0 y 2 ^ 16 – 1, es decir, entre 0 y 65535, pero es preferible usar abierto para todos los puertos.

Luego, abra esa dirección ip: Número de puerto en su navegador en cualquier dispositivo conectado a la misma red WiFi y disfrute del uso compartido de archivos WiFi .

2.Boolean también se toma como un entero en python:

a = [5,6,7,8,9]
print (a [True]) #prints 6
imprimir (un [Falso]) #prints 5

3. Oye, eso no es un truco, intercambiando dos números:

Sin ofender a ningún otro lenguaje de programación .

a, b = b, a # swap dos enteros sin variable adicional

4.Mergiendo dos diccionarios:

# Fusionando dos diccionarios
x = {‘v’: 1, ‘i’: 6, ‘s’: 3}
y = {‘s’: 7, ‘h’: 5, ‘a’: 8, ‘l’: 2}
z = {** x, ** y}
imprimir (z)

5. Número de conversiones del sistema

6. Obtener la última salida almacenada en el intérprete:

En el intérprete _ almacena el valor de la última salida.

7.Aplicar si, de otra manera, similar al operador ternario en C.

  • Concepto del punto 2 anterior.

a = int (entrada ())
imprimir (“Múltiple de 5”, “No es un múltiplo de 5”) [a% 5 == 0]

8. XKCD comic

importar antigravedad

El módulo antigravedad, que hace referencia al cómic XKCD que menciona Python,

9. Elementos del diccionario con mensaje de error.

número = {1: ‘uno’, 2: ‘dos’, 3: ‘tres’}
imprimir (número.get (4, “error: No definido”))

10.Zen de Python

importar esto

11. Calendario

calendario de importación
cal = calendar.month (2017,11)
imprimir (cal)

—————————

-Footnotes :

Creo que las estructuras de datos en el módulo de colecciones son herramientas eléctricas subutilizadas. Utilizo los contadores para representar funciones de probabilidad de masa, punto por defecto para acumular listas, y se nombran dos veces en lugar de escribir pequeñas definiciones de clase.

Tengo un cuaderno de notas que muestra contadores aquí: Página en ipython.org

Crear infinitos
El infinito, y su hermano menos infinito, es útil de vez en cuando.

my_inf = float (‘Inf’)
99999999> my_inf
-> falso

my_neg_inf = float (‘- Inf’)
mi_neg_inf> -99999999
-> falso

Comparaciones intuitivas
Un gran ejemplo de la simplicidad de la sintaxis de python.

x = 2
3> x == 1
-> falso
1 -> Verdadero
10 <10 * x <30
-> Verdadero
10
-> falso
100
= x ** 6 + 34> x <= 2 * x <5
-> Verdadero

Enumerarlo
¿Alguna vez has querido encontrar ese maldito índice cuando estás dentro de un bucle?

mylist = [4,2,42]
para i, valor en enumerar (mylist):
imprimir i, ‘:’, valor
-> 0: 4
-> 1: 2
-> 2: 42

Revertirla
Esto se ha convertido en parte de mi ritual matutino. Marcha atrás. En cualquier sitio. En cualquier momento. Todo el tiempo.

# Invertir la lista en sí:
mylist = [1,2,3]
mylist.reverse ()
imprimir mylist
-> [3,2,1]
# Iterar en reversa
para elemento en reversa ([1,2,3]): elemento de impresión
-> 3
-> 2
-> 1

Generador de listas ultra compactas
Al usar las listas de comprensión anidadas, puede ahorrar mucho escribiendo, mientras se divierte impresionando a las chicas.

[(x ** 2, y ** 2, x ** 2 + y ** 2) para x en el rango (1,5) para y en el rango (1,5) si x <= y y x% 2 = = 0]
-> [(4, 4, 8), (4, 9, 13), (4, 16, 20), (16, 16, 32)]

¡NÓTESE BIEN! Los nidos locos deben usarse con extrema precaución.

Legibilidad> Chicas
-> Verdadero

Llamada Splat
‘*’ se llama el operador splat y puede hacerte sonreír. Automáticamente despaca las cosas en una llamada de función.

def foo (a, b, c):
imprimir a, b, c

mydict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
mylist = [10, 20, 30]

foo (* mydict)
-> a, b, c
foo (** mydict)
-> 1, 2, 3
foo (* mylist)
-> 10 20 30

El lindo truco de cuerdas vacías
Al usar dos comillas simples (”) y un punto (.), Tenemos acceso a todas las funciones de cadena integradas. Esto puede ser útil, ya ves.

” .join (‘I’, ‘Want’, ‘Just’, ‘One’, ‘String’)
-> ‘IWantJustOneString’

Itertools
El módulo de itertools nos proporciona algunas funciones útiles y eficientes. Por ejemplo

de la cadena de importación itertools
” .join ((‘Hello’, ‘Kiddo’))
-> ‘Hola Kiddo’
” .join ((x para x en cadena (‘XCVGOHST’, ‘VSBNTSKFDA’) si x == ‘O’ o x == ‘K’))
-> ‘OK’

Cuando Las Vegas no es suficiente
Compre algo de cerveza, invite a algunos (exactamente 10) amigos y copie / pegue esta línea sexy de código de Python en su intérprete favorito. Las reglas son:
1. Presione Enter
2. ¡El que obtenga menos estrellas tiene que CHUG CHUG CHUG!
3. Presione la flecha hacia arriba
4. Ir a 1.

imprimir “\ n” .join (str (i) + “: \ t” + “*” * randint (1,10) para i en el rango (1,11))

Actualizar:

Hacer enums python
Me gusta este truco de enumeración:

clase PlayerRanking:
Perno, verde, Johnson, mamá = rango (4)

PlayerRanking.Mom
-> 4

Shell interactivo en python con ipython.

Es un potente terminal interactivo, útil para comprender métodos, argumentos y apidoc. Es muy útil para todos los programadores para acostumbrarse rápidamente a una biblioteca específica. Tiene soporte de línea de lectura en donde los nombres de los métodos se completan automáticamente.

Considere este escenario. Estás tratando con el camino. Te gusta saber la ruta completa para el directorio dado. Usted sabe que el método reside en la biblioteca os.path, pero no está seguro del nombre exacto del método. Puede usar ipython para averiguar el nombre del método correcto.

Importe la biblioteca y use la finalización de la pestaña para enumerar todos los métodos disponibles en la biblioteca, de manera similar a como hacemos la finalización del comando en bash. ¡Sencillo!

whitepearl:~ bhuvan$ ipython

En [1]: desde el camino de importación

En [2]: camino.
path.abspath path.altsep path.basename path.commonprefix path.curdir path.defpath
path.devnull path.dirname path.exists path.expanduser path.expandvars path.extsep
path.genericpath path.getatime path.getctime path.getmtime path.getsize path.isabs
path.isdir path.isfile path.islink path.ismount path.join path.lexists
path.normcase path.normpath path.os path.pardir path.pathsep path.realpath
path.relpath path.samefile path.sameopenfile path.samestat path.sep path.split
path.splitdrive path.splitext path.stat path.supports_unicode_filenames path.sys path.walk
path.warnings

En [2]: path.realpath?
Tipo: función
Clase base:
Forma de cadena:
Espacio de nombres: interactivo
Archivo: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
Definición: path.realpath (nombre de archivo)
Docstring:
Devuelve la ruta canónica del nombre de archivo especificado, eliminando cualquier
Enlaces simbólicos encontrados en el camino.

En [3]: path.realpath (‘.’)
Fuera [3]: ‘/ Users / bhuvan’

Yo y mi amigo nos estábamos preparando para entrevistas de colocación para varias compañías.
Yo, siendo de formación en ciencias informáticas, estoy definitivamente herido por los gigantes de la tecnología y definitivamente quería ser colocado en tales compañías. Para eso, también debemos revisar las preguntas de la entrevista anterior que se pueden encontrar en muchos sitios web en línea. Pero es bastante engorroso buscar esas preguntas cuando se las necesita y se necesita mucho tiempo para buscarlas. Así que junto con mi amigo pensé en una idea ..

Pensamos en desarrollar una aplicación que pueda hacernos esas preguntas en unos pocos clics. Pero para hacer eso, tenemos que vincular nuestra aplicación directamente a los múltiples sitios que no nos parecieron factibles. Así que en lugar de eso pensamos en mantener nuestra propia base de datos. Para eso, PYTHON vino a nuestro rescate.

Desarrollamos nuestra base de datos rastreando muchos de estos sitios web para tales preguntas, los dividimos en muchas subcategorías y creamos una aplicación que puede acceder fácilmente a esas preguntas de la manera más simple en solo 2-3 toques en la pantalla.

Aquí está el enlace de la aplicación:
Programming Interview Question – Aplicaciones de Android en Google Play

Python fue nuestra mejor apuesta para construir nuestra base de datos. Utilizamos Beautiful Soup para desechar muchos de estos sitios web. Construí el guión en cuestión de horas,
dejó el script ejecutándose durante la noche … y voila …. Obtuvo una enorme base de datos que contiene decenas de miles de tales preguntas.

Compartiéndolo aquí para que otros puedan beneficiarse de esto también.

No hay inglés y jerga de lujo.

Vamos a bucear directamente en.

Consejos básicos para aumentar la eficiencia de los scripts básicos de Python.

1.-Lugar de intercambio de dos números.

x, y = 10, 20

imprimir (x, y)

x, y = y, x

imprimir (x, y)

# 1 (10, 20)

# 2 (20, 10)

2.Protección del operador de comparación.

n = 10

resultado = 1

imprimir (resultado)

# Cierto

resultado = 1> n <= 9

imprimir (resultado)

# Falso

3.Uso de operadores ternarios para asignación condicional.

Sintaxis para usar el operador condicional en Python

[on_true] si [expresión] else [on_false]

Aquí hay algunos ejemplos que puede usar para hacer que su código sea compacto y conciso.

La siguiente declaración está haciendo lo mismo que se supone que es

Asigne 10 a x si y es 9, de lo contrario asigne 20 a x ”.

Podemos ampliar el encadenamiento de operadores si es necesario.

Pitón

x = 10 si (y == 9) más 20

Del mismo modo, podemos hacer lo mismo para los objetos de clase.

x = (classA si y == 1 else classB) (param1, param2)

En el ejemplo anterior, classA y classB son dos clases y uno de los constructores de clase sería llamado.

A continuación se muestra un ejemplo más con un no. de condiciones de unión para evaluar el número más pequeño.

pequeño def (a, b, c):

devuelve a si a <= b y a <= c else (b si b <= a y b <= c else c)

impresión (pequeño (1, 0, 1))

impresión (pequeño (1, 2, 2))

impresión (pequeño (2, 2, 3))

impresión (pequeño (5, 4, 3))

#Salida

# 0 # 1 # 2 # 3

Incluso podemos usar un operador ternario con la lista de comprensión.

[m ** 2 si m> 10 más m ** 4 para m en el rango (50)]

# => [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

Trabaja con cuerdas multilínea.

El enfoque básico es utilizar barras invertidas que se derivan del lenguaje C

multiStr = “select * from multi_row \

donde row_id <5 "

imprimir (multiStr)

# select * from multi_row donde row_id <5

Un truco más es usar las comillas triples.

multiStr = “” “select * from multi_row

donde row_id <5 "" "

imprimir (multiStr )

#select * de multi_row

#where row_id <5

El problema común con los métodos anteriores es la falta de sangría adecuada. Si intentamos sangrar, insertará espacios en blanco en la cadena.

Así que la solución final es dividir la cadena en varias líneas y encerrar toda la cadena entre paréntesis.

multiStr = (“select * from multi_row”

“donde row_id <5"

“orden por edad”)

imprimir (multiStr)

#select * de multi_row donde row_id <5 ordena por edad

Almacenar elementos de lista en una nueva variable

testList = [1,2,3]

x, y, z = testList

imprimir (x, y, z)

# -> 1 2 3

Imprime la ruta del archivo de los módulos importados.

subprocesos de importación

zócalo de importación

imprimir (enhebrar)

imprimir (socket)

# 1-

# 2-

Utilice el operador interactivo “_”.

> >> 2 + 1

3

>>> _

3

>>> imprimir _

3

Diccionario / conjunto de comprensiones.

testDict = {i: i * i para i en xrange (10)}

testSet = {i * 2 para i en xrange (10)}

imprimir (testSet)

imprimir (testDict)

#set ([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])

# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Nota- Solo hay una diferencia de <:> en las dos afirmaciones. Además, para ejecutar el código anterior en Python3, reemplaza por

Depuración de scripts.

importar pdb

pdb.set_trace ()

Podemos especificar en cualquier lugar del script y establecer un punto de interrupción allí. Es extremadamente conveniente.

Configuración de intercambio de archivos.

Python permite ejecutar un servidor HTTP que puede usar para compartir archivos desde el directorio raíz del servidor. A continuación se muestran los comandos para iniciar el servidor.

# Python 2

Cáscara

1

python -m SimpleHTTPServer

# Python 3

Cáscara

python3 -m http.server

Los comandos anteriores iniciarían un servidor en el puerto predeterminado, es decir, 8000. También puede usar un puerto personalizado pasándolo como último argumento a los comandos anteriores.

Inspecciona un objeto en python.

Podemos inspeccionar objetos en Python llamando al método dir (). Aquí hay un ejemplo simple.

prueba = [1, 3, 5, 7]

imprimir (dir (prueba))

Cáscara

[‘__add__’, ‘__class__’, ‘__contiene__’, ‘__delattr__’, ‘__delitem__’, ‘__delslice__’, ‘__doc__’, ‘__eqq’ ‘,’ __getat ”, ‘__eq__’ ‘,’ __ge__ ” __getslice__ ‘,’ __gt__ ‘,’ __hash__ ‘,’ __iadd__ ‘,’ __imul__ ‘,’ __init__ ‘,’ __iter__ ‘,’ __le__ ‘,’ __len__ ”, ‘__len__’, ‘__len__’ ‘ , ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__setsci__’, ‘nsetslice__’, ‘__sizeof__’ ‘ contar ‘,’ extender ‘,’ index ‘,’ insert ‘,’ pop ‘,’ remove ‘,’ reverse ‘,’ sort ‘]

Simplificar si enunciado.

Para verificar múltiples valores, podemos hacerlo de la siguiente manera.

si m en [1,3,5,7]:

en lugar de:

si m == 1 o m == 3 o m == 5 o m == 7:

Alternativamente, podemos usar ‘{1,3,5,7}’ en lugar de ‘[1,3,5,7]’ para ‘en’ operador porque ‘set’ puede acceder a cada elemento con O (1).

Detectar la versión de python en tiempo de ejecución

En ocasiones, es posible que no queramos ejecutar nuestro programa si el motor de Python actualmente en ejecución es menor que la versión compatible. Para lograr esto, puede utilizar el siguiente fragmento de código. También imprime la versión de Python actualmente utilizada en un formato legible.

sistemas de importación

#Detecta la versión de Python actualmente en uso.

Si no es hasattr (sys, “hexversion”) o sys.hexversion! = 50660080:

imprimir (“Lo sentimos, no estás ejecutando en Python 3.5 \ n”)

imprimir (“Actualiza a 3.5. \ n”)

sys.exit (1)

#Imprimir la versión de Python en un formato legible.

imprimir (“Versión actual de Python:”, sys.version)

Alternativamente, puede usar sys.version_info> = (3, 5) para reemplazar sys.hexversion! = 50660080 en el código anterior. Fue una sugerencia de uno de los lectores informados.

Salida cuando se ejecuta en Python 2.7.

Python 2.7.10 (predeterminado, 14 de julio de 2015, 19:46:27)

[GCC 4.8.2] en linux

Lo sentimos, no estás corriendo en Python 3.5

Por favor actualice a 3.5.

Combinando múltiples cadenas.

Si desea concatenar todos los tokens disponibles en una lista, consulte el siguiente ejemplo.

prueba = [‘I’, ‘Me gusta’, ‘Python’, ‘automatización’]

Ahora, vamos a crear una sola cadena a partir de los elementos en la lista dada anteriormente.

>>> print ” .join (test)

Cuatro formas de revertir cadenas / lista.

Invertir la propia lista.

testList = [1, 3, 5]

testList.reverse ()

imprimir (testList)

# -> [5, 3, 1]

# Invertir mientras iterando en un bucle.

para elemento en reversa ([1,3,5]): imprimir (elemento)

# 1-> 5

# 2-> 3

# 3-> 1

# Invertir una cadena en línea.

“Prueba Python” [:: – 1]

Esto da la salida como “nohtyP tseT”

# Invertir una lista usando rebanado.

[1, 3, 5] [:: – 1]

El comando anterior dará la salida como [5, 3, 1].

Jugar con la enumeración.

Con los enumeradores, es fácil encontrar un índice mientras está dentro de un bucle.

lista de pruebas = [10, 20, 30]

para i, valor en enumerar (lista de prueba):

imprimir (i, ‘:’, valor)

# 1-> 0: 10

# 2-> 1: 20

# 3-> 2: 30

Uso de enumeraciones en python.

Podemos usar el siguiente enfoque para crear definiciones de enumeración.

Formas de clase:

Círculo, Cuadrado, Triángulo, Cuadrángulo = rango (4)

imprimir (Shapes.Circle)

imprimir (Shapes.Square)

imprimir (Shapes.Triangle)

imprimir (Shapes.Quadrangle)

# 1-> 0

# 2-> 1

# 3-> 2

# 4-> 3

Devuelve múltiples valores de la función.

No muchos lenguajes de programación soportan esta característica. Sin embargo, las funciones en Python devuelven múltiples valores.

Consulte el siguiente ejemplo para verlo funcionar.

# función que devuelve múltiples valores.

def x ():

devuelve 1, 2, 3, 4

# Llamando a la función anterior.

a, b, c, d = x ()

imprimir (a, b, c, d)

# -> 1 2 3 4

Desempaquete el argumento de la función usando el operador splat

El operador splat ofrece una forma artística de desempaquetar listas de argumentos. Por favor, consulte el siguiente ejemplo para mayor claridad.

prueba de def (x, y, z):

imprimir (x, y, z)

testDict = {‘x’: 1, ‘y’: 2, ‘z’: 3}

testList = [10, 20, 30]

prueba (* testDict)

prueba (** testDict)

test (* testList)

# 1-> xyz

# 2-> 1 2 3

# 3-> 10 20 30

Utilice un diccionario para almacenar un interruptor.

Podemos hacer un diccionario de expresiones de la tienda.

stdcalc = {

‘suma’: lambda x, y: x + y,

‘resta’: lambda x, y: x – y

}

print (stdcalc [‘sum’] (9,3))

imprimir (stdcalc [‘restar’] (9,3))

# 1-> 12

# 2-> 6

Calcula el factorial de cualquier número en una línea.

Python 2.X.

resultado = (lambda k: reduce (int .__ mul__, rango (1, k + 1), 1)) (3)

imprimir (resultado)

# -> 6

Python 3.X.

funciones de importación

resultado = (lambda k: functools.reduce (int .__ mul__, rango (1, k + 1), 1)) (3)

imprimir (resultado)

# -> 6

Encuentra el valor más frecuente en una lista.

prueba = [1,2,3,4,2,2,3,1,4,4,4]

imprimir (max (set (test), key = test.count))

# -> 4

Restablecer el límite de recursión.

sistemas de importación

x = 1001

imprimir (sys.getrecursionlimit ())

sys.setrecursionlimit (x)

imprimir (sys.getrecursionlimit ())

# 1-> 1000

# 2-> 1001

Compruebe el uso de memoria de un objeto.

En Python 3.5.

sistemas de importación

x = 1

imprimir (sys.getsizeof (x))

# -> 28

Utilice __slots__ para reducir los gastos generales de memoria.

¿Alguna vez has observado que tu aplicación Python consume muchos recursos, especialmente memoria? Aquí hay un truco que usa la variable de clase <__slots__> para reducir la sobrecarga de memoria en cierta medida.

sistemas de importación

clase FileSystem (objeto):

def __init __ (auto, archivos, carpetas, dispositivos):

self.files = archivos

self.folders = carpetas

self.devices = dispositivos

imprimir (sys.getsizeof (sistema de archivos))

clase FileSystem1 (objeto):

__slots__ = [‘archivos’, ‘carpetas’, ‘dispositivos’]

def __init __ (auto, archivos, carpetas, dispositivos):

self.files = archivos

self.folders = carpetas

self.devices = dispositivos

imprimir (sys.getsizeof (FileSystem1))

#En Python 3.5

# 1-> 1016

# 2-> 888

Claramente, se puede ver en los resultados que hay ahorros en el uso de la memoria. Pero debe usar __slots__ cuando la sobrecarga de memoria de una clase es innecesariamente grande. Hazlo solo después de perfilar la aplicación. De lo contrario, hará que el código sea difícil de cambiar y sin ningún beneficio real.

Lambda para imitar la función de impresión.

sistemas de importación

lprint = lambda * args: sys.stdout.write (“” .join (map (str, args)))

lprint (“python”, “tips”, 1000,1001 )

# -> puntas de pitón 1000 1001

Crea un diccionario a partir de dos secuencias repetidas.

t1 = (1, 2, 3)

t2 = (10, 20, 30)

imprimir (dict (zip (t1, t2)))

# -> {1: 10, 2: 20, 3: 30}

Búsqueda en línea de múltiples prefijos en una cadena.

imprimir (“ http: //www.google.com&quot ; .startswith ((” http: // “,” https: // “)))

imprimir (“ http: //www.google.co.uk&quot ; .endswith ((“. com “,”. http://co.uk “)))

# 1-> Verdadero

# 2-> Verdadero

Forma una lista unificada sin utilizar ningún bucle.

importar itertools

prueba = [[-1, -2], [30, 40], [25, 35]]

imprimir (lista (itertools.chain.from_iterable (prueba)))

# -> [-1, -2, 30, 40, 25, 35]

Implementar un verdadero cambio de caja en python.

Aquí hay un código para eso.

def xswitch (x):

devolver xswitch._system_dict.get (x, Ninguno)

xswitch._system_dict = {‘archivos’: 10, ‘carpetas’: 5, ‘dispositivos’: 2}

imprimir (xswitch (‘predeterminado’))

imprimir (xswitch (‘dispositivos’))

# 1-> Ninguno

# 2-> 2

El selenio de Python es realmente genial. Podemos realizar muchas cosas como seguir / dejar de seguir personas en quora. Inicie sesión en facebook, instagram, zomato, quora, etc. Obtenga vistas en un sitio web.

Trucos de Selenio Python

Los enlaces de Selenium Python proporcionan una API conveniente para acceder a Selenium Web Driver como Firefox, Chrome, etc.

¿Qué es webdriver?
Selenium WebDriver es una herramienta de prueba de automatización. Cuando digo automatización, significa que automatiza los scripts de prueba escritos en Selenium.

Enlace de instalación de Webdriver

Chrome: https://sites.google.com/a/chrom

Biblioteca importada

desde Selenium Import Webdriver

tiempo de importación

(i) Biblioteca de Selenio:
– Utilizado para la automatización
– Control Webdriver
– Realizar acciones como: clics de elementos, página de actualización, ir al enlace del sitio web, etc.

(ii) Biblioteca de tiempo:
-Para usar la función de reposo porque el selenio funciona solo cuando se cargan todos los elementos de la página. (Aunque también podemos usar espera implícita)

Trick1: ¿Cómo aumentar el recuento de vistas en un sitio web?
#Nota: Esto no funcionará en todos los sitios web, como youtube.
Lo que estaríamos aprendiendo es actualizar la página web una y otra vez después de un intervalo de tiempo determinado.

#! / usr / bin / env python
desde Selenium Import Webdriver
tiempo de importación
# establece la ruta del controlador web aquí puede variar
browser = webdriver.Chrome (executable_path = “C: \ Archivos de programa (x86) \ Google \ Chrome \ chromedriver.exe”)
website_URL = ” https://www.google.co.in/&quot ;
browser.get (website_URL)
# Después de cuántos segundos desea actualizar la página web
# Pocas vistas del sitio web si te quedas allí
# por un tiempo particular
# tienes que resolver eso
refreshrate = int (15)
# Esto seguiría funcionando hasta que detengas el compilador.
mientras que True
time.sleep (actualizar)
browser.refresh ()

Trick2: Cómo iniciar sesión en un sitio web, aquí tomamos un ejemplo de Zomato

desde Selenium Import Webdriver
# Para usar la función dormir porque el selenio.
# funciona solo cuando todos los elementos de la
# la página está cargada.
tiempo de importación
# conjunto de rutas webdriver
browser = webdriver.Chrome (“C: \ Archivos de programa (x86) \ Google \ Chrome \ chromedriver.exe”)
# Para maximizar la ventana del navegador
browser.maximize_window ()
# conjunto de enlaces zomato
browser.get (‘ https://www.zomato.com / ncr’)
time.sleep (3)
# Ingrese su nombre de usuario y contraseña aquí.
username = “shauryauppal” #cambialo
password = “test” #cambiala
# elemento de inicio de sesión hecho clic
browser.find_element_by_xpath (“// a [@id = ‘signin-link’]”). haga clic en ()
time.sleep (2)
# Inicio de sesión hecho clic
browser.find_element_by_xpath (“// a [@id = ‘login-email’]”). haga clic en ()
# nombre de usuario enviar
a = browser.find_element_by_xpath (“// input [@id = ‘ld-email’]”)
a.send_keys (nombre de usuario)
# contraseña enviar
b = browser.find_element_by_xpath (“// input [@id = ‘ld-password’]”)
b.send_keys (contraseña)
# botón de enviar presionado
browser.find_element_by_xpath (“// input [@id = ‘ld-submit-global’]”). haga clic en ()
imprimir (‘Iniciar sesión con éxito’)
browser.close ()

Trick3: inicio de sesión de Instagram en segundos
Iniciar sesión en Instagram en pocos segundos.

desde Selenium Import Webdriver
# Para usar la función dormir porque el selenio.
# funciona solo cuando todos los elementos del
# la página está cargada.
tiempo de importación
browser = webdriver.Chrome (“C: \ Archivos de programa (x86) \ Google \ Chrome \ chromedriver.exe”)

followlink = ” https://www.instagram.com/narendramodi/&quot ; #Puedes pegar cualquier ID
username = “shaurya” #Ingresa tu ID
password = “test” # Ingrese su contraseña
browser.get (followlink)
time.sleep (3)

browser.find_element_by_xpath (“// a [@class = ‘_ l8p4s’] [2]”). click ()
time.sleep (3)

a = browser.find_element_by_xpath (“// div [@class = ‘_ t296e’] [1] / div [1] / input [1]”)
a.send_keys (nombre de usuario)

b = browser.find_element_by_xpath (“// div [@class = ‘_ t296e’] [2] / div [1] / input [1]”)
b.send_keys (contraseña)

browser.find_element_by_xpath (“// button [@class = ‘_ qv64e _gexxb _4tgw8 _njrw0’]”). click ()
time.sleep (2)
browser.get (followlink)

Trick4: Facebook Login & Cómo tomar una captura de pantalla de la página web
Aquí tomamos dos capturas de pantalla antes de iniciar sesión y después de iniciar sesión

desde Selenium Import Webdriver
browser = webdriver.Chrome (“C: \ Archivos de programa (x86) \ Google \ Chrome \ chromedriver.exe”)
browser.maximize_window ()
username = “[email protected]
contraseña = “prueba”
browser.get (” https: //www.facebook.com&quot
browser.implicitly_wait (3)
browser.find_element_by_xpath (‘// * [@ id = “email”]’). send_keys (nombre de usuario)
browser.find_element_by_xpath (‘// * [@ id = “pass”]’). send_keys (contraseña)
# ¿Cómo se ve la página web antes de iniciar sesión?
browser.get_screenshot_as_file (“Facebook.png”)
browser.find_element_by_id (“loginbutton”). haga clic en ()
# ¿Cómo se ve la página web después de iniciar sesión?
browser.get_screenshot_as_file (“Facebook1.png”)

Resumen:
Trucos que aprendimos: –
1. Cómo aumentar no. de vista en un sitio web / página de actualización.
2. Zomato Login
3. sesión de Instagram
4. Inicio de sesión de Facebook y cómo tomar ScreenShot

Espero que quien lea esto aprenda algo. Prueba estos scripts que te gustarán.

#HappyCoding.

Edición: en caso de que alguien sepa aprender a encontrar Xpath, esta es la fuente desde donde lo estudié. XPath: XPath significa XML Path Language, que se utiliza para encontrar un elemento en una página web. Puede encontrarlo fácilmente utilizando el elemento inspeccionar.

La fiebre de la Copa Mundial de Cricket está en marcha y todos en mi oficina solían visitar sitios web como cricinfo y cricbuzz para ver las últimas puntuaciones.

Resulta que usé una máquina ubuntu aquí en mi oficina para escribir un simple script en Python para obtener la última puntuación de cricket y enviarme una notificación cada 1 minuto.

Aquí está el guión:

#!/usr/bin/env python2
import requests
from bs4 import BeautifulSoup
import pynotify
from time import sleep
def sendmessage(title, message):
pynotify.init("Test")
notice = pynotify.Notification(title, message)
notice.show()
return
url = "http://static.cricinfo.com/rss/livescores.xml"
while True:
r = requests.get(url)
while r.status_code is not 200:
r = requests.get(url)
soup = BeautifulSoup(r.text)
data = soup.find_all("description")
score = data[1].text
sendmessage("Score", score)
sleep(60)

Aquí hay una captura de pantalla del guión en acción, mientras que la semifinal entre Nueva Zelanda y Sudáfrica está en:


El código debe ejecutarse en cualquier máquina Linux donde esté instalado libnotify, siempre que los módulos de Python importados estén allí en su máquina.
Ahora estoy pensando en modificar la secuencia de comandos para que reciba una notificación cada vez que se califiquen las ejecuciones o se tome una ventanilla, en lugar de enviarme una notificación cada minuto.

EDITAR: Quién sabe en qué se puede convertir este guión. Lo he puesto en mi github aquí: https://github.com/neo1691/score
Siéntete libre de contribuir a ello. Gracias

EDIT2: Por favor, eche un vistazo a la versión github de scorer.py. Ha evolucionado mucho. Gracias.

Enumerar

En lugar de hacer:

i = 0
para el artículo en iterable:
imprimir i, artículo
i + = 1

Podemos hacer:

para i, artículo en enumerar (iterable):
imprimir i, artículo

Enumerar también puede tomar un segundo argumento. Aquí hay un ejemplo:

>>> lista (enumerar (‘abc’))
[(0, ‘a’), (1, ‘b’), (2, ‘c’)]

>>> lista (enumerar (‘abc’, 1))
[(1, ‘a’), (2, ‘b’), (3, ‘c’)]

Dict / Set comprensiones

Es posible que sepa acerca de las listas de comprensión, pero es posible que no esté al tanto de las comprensiones dict / set . Son simples de usar y igual de efectivos. Aquí hay un ejemplo:

my_dict = {i: i * i para i en xrange (100)}
my_set = {i * 15 para i en xrange (100)}

# Solo hay una diferencia de ‘:’ en ambos

Forzando la división del flotador:

Si dividimos números enteros, Python nos da el resultado como un número entero, incluso si el resultado fue un flotador. Para evitar este problema, tenemos que hacer algo como esto:

resultado = 1.0 / 2

Pero hay otra manera de resolver este problema del cual ni yo estaba al tanto. Tu puedes hacer:

de __futura__ división de importación
resultado = 1/2
# imprimir (resultado)
# 0.5

Voila! Ahora no necesita agregar .0 para obtener una respuesta precisa. Ten en cuenta que este truco es solo para Python 2. En Python 3 no hay necesidad de realizar la importación ya que maneja este caso de forma predeterminada.

Servidor simple

¿Desea compartir archivos de un directorio rápida y fácilmente? Simplemente puedes hacer:

# Python2
python -m SimpleHTTPServer

# Python 3
python3 -m http.server

Esto iniciaría un servidor.

Evaluando expresiones de Python

Todos sabemos acerca de eval, pero ¿todos sabemos acerca de literal_eval ? Talvez no. Tu puedes hacer:

importación de ast
my_list = ast.literal_eval (expr)

En lugar de:

expr = “[1, 2, 3]”
my_list = eval (expr)

Estoy seguro de que es algo nuevo para la mayoría de nosotros, pero ha sido parte de Python durante mucho tiempo.

Perfilando un guion

Puede fácilmente crear un perfil de un script ejecutándolo de esta manera:

python -m cProfile my_script.py

Introspección de objetos

Puedes inspeccionar objetos en Python usando dir (). Aquí hay un ejemplo simple:

>>> foo = [1, 2, 3, 4]
>>> dir (foo)
[‘__add__’, ‘__class__’, ‘__contains__’,
‘__delattr__’, ‘__delitem__’, ‘__delslice__’,…,
‘extender’, ‘index’, ‘insert’, ‘pop’, ‘remove’,
‘invertir’, ‘ordenar’]

Depuración de scripts

Puede establecer fácilmente puntos de interrupción en su script utilizando el módulo pdb . Aquí hay un ejemplo:

importar pdb
pdb.set_trace ()

Puede escribir pdb.set_trace () en cualquier parte de su script y establecerá un punto de interrupción allí. Super conveniente También deberías leer más sobre pdb, ya que también tiene un par de otras gemas ocultas.

Simplificar si se construye.

Si tiene que verificar varios valores, puede hacerlo fácilmente:

si n en [1,4,5,6]:

en lugar de:

si n == 1 o n == 4 o n == 5 o n == 6:

Invertir una lista / cadena

Puedes revertir rápidamente una lista usando:

>>> a = [1,2,3,4]
>>> a [:: – 1]
[4, 3, 2, 1]

# Esto crea una nueva lista invertida.
# Si desea revertir una lista en su lugar, puede hacer:

a.reverse ()

y lo mismo se puede aplicar a una cadena también:

>>> foo = “yasoob”
>>> foo [:: – 1]
abucheo

Impresión bonita

Puede imprimir dados y listas de una manera hermosa haciendo:

desde pprint import pprint
pprint (my_dict)

Esto es más efectivo en los dicts. Además, si desea imprimir bastante json rápidamente desde un archivo, simplemente puede hacer:

cat file.json | python -m json.tools

Operadores Ternarios

Los operadores ternarios son atajos para una sentencia if-else y también se conocen como operadores condicionales. Aquí hay algunos ejemplos que puede usar para hacer que su código sea compacto y más hermoso.

[on_true] si [expresión] else [on_false]
x, y = 50, 25
pequeño = x si x

Este es el truco coooool en Python que vi en internet mientras buscaba el ” Mapa de India en Python ” …

Creando visualizaciones de mapas en <10 líneas de Python:

13-10-07 Actualización: consulte la documentación de Vincent para ver la sintaxis actualizada del trazado de mapas. Una nueva publicación sobre mapas (con ejemplos mejorados) se puede encontrar aquí.

importación vincent
world_countries = r’world-countries.json ‘
world = vincent.Map (ancho = 1200, altura = 1000)
world.geo_data (projection = ‘winkel3’, scale = 200, world = world_countries)
world.to_json (ruta)

Uno de mis objetivos cuando comencé a construir Vincent era racionalizar la creación de mapas tanto como fuera posible. Hay algunas bibliotecas excelentes de mapas de Python por ahí, vea Basemap y Kartograph para más diversión con los mapas. Recomiendo ambas herramientas, ya que son bastante buenas y muy potentes. Quería algo un poco más simple, que se basa en el poder de Vega y permite un simple punto de sintaxis para archivos geoJSON, especificar una proyección y una escala / tamaño, generar el mapa.

Por ejemplo, agrupar conjuntos de datos de mapas para crear mapas más complejos:

vis = vincent.Map (ancho = 1000, alto = 800)
#Agregue los datos del condado de EE. UU. Y una nueva línea de color
vis.geo_data (projection = ‘albersUsa’, scale = 1000, counties = county_geo)
vis + (‘2B4ECF’, ‘marks’, 0, ‘properties’, ‘enter’, ‘stroke’, ‘value’)

#Agregue los datos de estado, elimine el relleno, escriba el resultado de la especificación Vega en JSON
vis.geo_data (estados = estado_geo)
vis – (‘fill’, ‘marks’, 1, ‘properties’, ‘enter’)
vis.to_json (ruta)

Además, los mapas de coropletas pedían un enlace al Pandas DataFrame, con las columnas de datos asignadas directamente a las características del mapa. Suponiendo una asignación 1: 1 de las características de geoJSON a los datos de columna, la sintaxis es muy sencilla:

# ‘fusionado’ es el DataFrame de Pandas
vis = vincent.Map (ancho = 1000, alto = 800)
vis.tabular_data (fusionado, columnas = [‘FIPS_Code’, ‘Unemployment_rate_2011’])
vis.geo_data (projection = ‘albersUsa’, scale = 1000, bind_data = ‘Portal Data Indonesia’, condados = county_geo)
vis + ([“# f5f5f5”, “# 000045”], ‘escalas’, 0, ‘rango’)
vis.to_json (ruta)

Esto no está exento de un poco de organización y transformación de datos: el usuario debe asegurarse de que haya una asignación 1: 1 de las claves en geoJSON a las claves de fila en el Pandas DataFrame. Esto es lo que se requería para obtener un DataFrame limpio para la asignación del ejemplo anterior: los datos de nuestro condado son un csv con el código FIPS, el nombre del condado y nuestros datos económicos (nombres de columna retenidos):

00000, EE. UU., Estados Unidos, 154505871,140674478,13831393,9,50502,100
01000, AL, Alabama, 2190519,1993977,196542,9,41427,100
01001, AL, Condado de Autauga, 25930,23854,2076,8,48863,117.9
01003, AL, condado de Baldwin, 85407,78491,6916,8.1,50144,121
01005, AL, condado de Barbour, 9761,8651,1110,11.4,30117,72.7

Y los polígonos de nuestro condado en un geoJSON con códigos FIPS como id (gracias a la gente de Trifacta por esta información). Los polígonos reales se han truncado aquí por brevedad, consulte los datos de ejemplo para el conjunto de datos completo:

{“type”: “FeatureCollection”, “features”: [
{“type”: “Feature”, “id”: “1001”, “properties”: {“name”: “Autauga”}
{“type”: “Feature”, “id”: “1003”, “properties”: {“name”: “Baldwin”}
{“type”: “Feature”, “id”: “1005”, “properties”: {“name”: “Barbour”}
{“type”: “Feature”, “id”: “1007”, “properties”: {“name”: “Bibb”}
{“type”: “Feature”, “id”: “1009”, “properties”: {“name”: “Blount”}
{“type”: “Feature”, “id”: “1011”, “properties”: {“name”: “Bullock”}
{“type”: “Feature”, “id”: “1013”, “properties”: {“name”: “Butler”}
{“type”: “Feature”, “id”: “1015”, “properties”: {“name”: “Calhoun”}
{“type”: “Feature”, “id”: “1017”, “properties”: {“name”: “Chambers”}
{“type”: “Feature”, “id”: “1019”, “properties”: {“name”: “Cherokee”}

Necesitamos coincidir con los códigos FIPS y asegurarnos de que las coincidencias sean exactas, o Vega no comprimirá los datos correctamente:

importar json
importar pandas como pd
#Mapa los códigos de condado que tenemos en nuestra geometría a los de la
Archivo #county_data, que contiene filas adicionales que no necesitamos
con open (county_geo, ‘r’) como f:
get_id = json.load (f)

#Agrupe los códigos FIPS y cárguelos en un marco de datos
county_codes = [x [‘id’] para x en get_id [‘features’]]
county_df = pd.DataFrame ({‘FIPS_Code’: county_codes}, dtype = str)

# Leer en el marco de datos, convertir a cadena para la coherencia
df = pd.read_csv (county_data, na_values ​​= [”])
df [‘FIPS_Code’] = df [‘FIPS_Code’]. astype (str)

# Realice una unión interna, rellene las NA con los datos del condado más cercano
fusionado = pd.merge (df, county_df, on = ‘FIPS_Code’, how = ‘inner’)
fusionado = merged.fillna (method = ‘pad’)

>>> merged.head ()
FIPS_Code State Area_name Civilian_labor_force_2011 Employed_2011 \
0 1001 AL Autauga County 25930 23854
1 1003 AL Baldwin County 85407 78491
2 1005 AL Condado de Barbour 9761 8651
3 1007 AL Bibb Condado 9216 8303
4 1009 AL Blount County 26347 24156

Unemployed_2011 Unemployment_rate_2011 Median_Household_Income_2011 \
0 2076 8.0 48863
1 6916 8.1 50144
2 1110 11.4 30117
3 913 9.9 37347
4 2191 8.3 41940

Med_HH_Income_Percent_of_StateTotal_2011
0 117.9
1 121.0
2 72.7
3 90.2
4 101.2

Y ahora podemos generar rápidamente diferentes coropletas:

vis.tabular_data (fusionado, columnas = [‘FIPS_Code’, ‘Civilian_labor_force_2011’])
vis.to_json (ruta)

Eso no nos dice mucho más que los condados de LA y King que son muy grandes y muy poblados. Echemos un vistazo a la mediana de ingresos del hogar:

vis.tabular_data (fusionado, columnas = [‘FIPS_Code’, ‘Median_Household_Income_2011’])
vis.to_json(path)

Certainly some high income areas on the east coast and in other high density areas. I bet this would be more interesting on the city level, but that will have to wait for a future post. Lets quickly reset the map and look at state unemployment:

#Swap county data for state data, reset map
state_data = pd.read_csv(state_unemployment)
vis.tabular_data(state_data, columns=[‘State’, ‘Unemployment’])
vis.geo_data(bind_data=’Portal Data Indonesia’, reset=True, states=state_geo)
vis.update_map(scale=1000, projection=’albersUsa’)
vis + ([‘#c9cedb’, ‘#0b0d11’], ‘scales’, 0, ‘range’)
vis.to_json(path)

Source: wrobstory

And the second one is, (I already posted this answer for a question in Quora, but this question will need this answer.)

The author of this content is: Mr. Praveen Kumar.

A few years ago, when I was in college, I attended a workshop organized by FOSSEE and it was in this workshop that I met “Python” and fell in love with her at first sight. I was amazed at how easy it was to write simple solutions to complex problems in Python. One of the utility I learnt at the workshop was an image to ASCII art generator.

¿Cómo funciona?

We scale a given image to a standard resolution that suitably represents the ASCII version of a given image. The scaled version is then converted to a grayscale image. In a grayscale image, there are 256 shades of gray, or in other words, each pixel carries only the intensity information which is represented by an 8 bit value. A pixel with a value of 0 is assumed to be black and the one with 255 is assumed to be white. We divide the whole range of 0-255 into 11 smaller ranges of 25 pixels each and then assign each pixel a character according to the range it falls in. The point is to assign a group of pixels with slightly varying intensity the same ASCII char. We use the PIL library to play with the images. The code given below is almost self explanatory. The default char mapping and resolution doesn’t render good ASCII arts for every image size and so you should try modifying the char mapping and image size to the one that best represents the given image.

Here are some ASCII arts:

Dependencies:

PIL(Python Imaging Library)

Under Ubuntu

$ sudo pip install Pillow

Code:

ASCII_CHARS = [ ‘#’, ‘?’, ‘%’, ‘.’, ‘S’, ‘+’, ‘.’, ‘*’, ‘:’, ‘,’, ‘@’]

def scale_image(image, new_width=100):
“””Resizes an image preserving the aspect ratio.
“””
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)

new_image = image.resize((new_width, new_height))
return new_image

def convert_to_grayscale(image):
return image.convert(‘L’)

def map_pixels_to_ascii_chars(image, range_width=25):
“””Maps each pixel to an ascii char based on the range
in which it lies.

0-255 is divided into 11 ranges of 25 pixels each.
“””

pixels_in_image = list(image.getdata())
pixels_to_chars = [ASCII_CHARS[pixel_value/range_width] for pixel_value in
pixels_in_image]

return “”.join(pixels_to_chars)

def convert_image_to_ascii(image, new_width=100):
image = scale_image(image)
image = convert_to_grayscale(image)

pixels_to_chars = map_pixels_to_ascii_chars(image)
len_pixels_to_chars = len(pixels_to_chars)

image_ascii = [pixels_to_chars[index: index + new_width] for index in
xrange(0, len_pixels_to_chars, new_width)]

return “\n”.join(image_ascii)

def handle_image_conversion(image_filepath):
image = None
try:
image = Image.open(image_filepath)
except Exception, e:
print “Unable to open image file {image_filepath}.”.format(image_filepath=image_filepath)
print e
regreso

image_ascii = convert_image_to_ascii(image)
print image_ascii

if __name__==’__main__’:
import sys

image_file_path = sys.argv[1]
handle_image_conversion(image_file_path)Source : Beautiful Python: A Simple ASCII Art Generator from Images – Praveen Kumar

Source: Beautiful Python: A Simple ASCII Art Generator from Images – Praveen Kumar

Gracias…. 🙂

I’m a bit amazed that this hasn’t come up here yet. Stack Overflow is a repository of such tips and tricks, you just need to dig a bit deeper. Here are some of the most comprehensive list of lesser known but useful features of python:

Hidden features of Python

Similar lists also exist for:

Hidden features of C
Hidden Features of C++?
tips and tricks – Hidden Features of C#? – Stack Overflow
Hidden Features of Java
Hidden Features of JavaScript?
Hidden features of HTML
Hidden features of CSS
Hidden Features of PHP?
Hidden Features of VB.NET?
.net – Hidden Features of ASP.NET – Stack Overflow
Hidden features of Ruby
Hidden Features of Ruby on Rails
Hidden features of Perl?

You’re most welcome! 🙂

List comprehensions and generator expressions

Instead of building a list with a loop:

b = []
for x in a:
b.append(10 * x)
foo(b)

you can often build it much more concisely with a list comprehension :

foo([10 * x for x in a])

or, if foo accepts an arbitrarily iterable (which it usually will), a generator expression :

foo(10 * x for x in a)

Python 2.7 supports dict and set comprehensions, too:

>>> {x: 10 * x for x in range(5)}
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
>>> {10 * x for x in range(5)}
set([0, 40, 10, 20, 30])

Fun tricks with zip

Transposing a matrix:

>>> l = [[1, 2, 3], [4, 5, 6]]
>>> zip(*l)
[(1, 4), (2, 5), (3, 6)]

Dividing a list into groups of n :

>>> l = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8]
>>> zip(*[iter(l)] * 3)
[(3, 1, 4), (1, 5, 9), (2, 6, 5), (3, 5, 8)]

import this

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

I’m not sure, whether these things are tricks – you would down-vote me in the worst case 😉

adding to *.py script #!/usr/bin/env python line, make it executable and run by: ./script.py

generating HTML documentation : pydoc -w ./script.py

else statement after for/while loops (go into, if there was no break)

What I have ?
pip freeze
Is there something ?
pip search something
Do I need something ?
pip install something

We can not:

def yetanotherfunc():
yaf_int = 1
def childfunc():
global yaf_int
yaf_int = 3

but we can:

def yetanotherfunc():
yaf_int = [1]
def childfunc():
yaf_int[0] = 3

deep copy:

import copy
sth_deepcopy = copy.deepcopy(sth)

Why do we have “private” attributes in Python:
http://stackoverflow.com/questio

for in protocole:
Understanding Python’s “for” statement

Generators can be use as alternative to callbacks – for example yields if there some big data has arrived.

Herramientas:
virualenv
pdb debugger (pdb.set_trace() feature)
pylint for code analysis

Bare with me if any of the tricks given below have been mentioned before. I didn’t read all of the answers.

Use C-Style Braces Instead of Indentation to Denote Scopes

>>> from __future__ import braces

Unpacking

>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)
>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)
>>> a, b, c = (2 * i + 1 for i in range(3))
>>> a, b, c
(1, 3, 5)
>>> a, (b, c), d = [1, (2, 3), 4]
>>> a
1
>>> b
2
>>> c
3
>>> d
4

Reversing a string in Python

>>> a = “arihant”
>>> print “Reverse is”,a[::-1]
Reverse is tnahira

Transposing a Matrix

>>> mat = [[1, 2, 3], [4, 5, 6]]
>>> zip(*mat)
[(1, 4), (2, 5), (3, 6)]

a = [1,2,3]

Store all three values of the list in 3 new variables

>>> a = [1, 2, 3]
>>> x, y, z = a
>>> x
1
>>> y
2
>>> z
3

a = [“Arihant”, “Bansal”, “Python”, “Developer”]

Create a single string from all the elements in list above.

>>> print ” “.join(a)
Arihant Bansal Python Developer

Swap two numbers with one line of code.

>>> a=7
>>> b=5
>>> b, a =a, b
>>> a
5
>>> b
7

Negative indexing

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[-1]
10
>>> a[-3]
8

Start a static HTTP server

Do you want to quickly and easily share files from a directory? You can simply do:

# Python2
python -m SimpleHTTPServer

# Python 3
python3 -m http.server

This would start up a server.

Enumerate

Instead of doing:

i = 0
for item in iterable:
print i, item
i += 1

We can do:

for i, item in enumerate(iterable):
print i, item

Enumerate can also take a second argument. Aquí hay un ejemplo:

>>> list(enumerate(‘abc’))
[(0, ‘a’), (1, ‘b’), (2, ‘c’)]

>>> list(enumerate(‘abc’, 1))
[(1, ‘a’), (2, ‘b’), (3, ‘c’)]

Forcing float division:

If we divide whole numbers Python gives us the result as a whole number even if the result was a float. In order to circumvent this issue we have to do something like this:

result = 1.0/2

But there is another way to solve this problem which even I wasn’t aware of. You can do:

from __future__ import division
result = 1/2
# print(result)
# 0.5

Voila! Now you don’t need to append .0 in order to get an accurate answer. Do note that this trick is for Python 2 only. In Python 3 there is no need to do the import as it handles this case by default.

Simplify if constructs

If you have to check for several values you can easily do:

if n in [1,4,5,6]:

en lugar de:

if n==1 or n==4 or n==5 or n==6:

Ternary Operators

Ternary operators are shortcut for an if-else statement, and are also known as a conditional operators. Here are some examples which you can use to make your code compact and more beautiful.

[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y

startswith parameters

En lugar de:

if s.startswith('http://') or s.startswith('https://'):

You can do:

if s.startswith(('http://', 'https://')):

NOTE: And the same with endswith and isinstance(1, (int, float))

Thats all for today! I hope you enjoyed this answer and picked up a trick or two along the way.

Thanks for the A2A Tanzeel Ahmed

A geek way to wish Happy Birthday!

There is nothing more awesome than doing regular things in a geeky way. Few days back I was wondering what would be the geekiest way to wish someone happy birthday. It should be geeky alright, but should also have regular things like cake + candles + birthday song + wishing happy birthday .

Now mixing all this with my very little knowledge in signal processing, I wrote a python code which does this:

A virtual cake on terminal who’s shade has an equalizer effect corresponding to the “happy birthday” song that is played in the background. Here, the cake has candles with flames fluttering randomly. Also, we have a fancy display of happy birthday message.

Snap of the virtual cake:

How it works?

Read my blog post: A geek way to wish Happy Birthday!.
Source on Github: alseambusher/HappyBirthday-term

Here is the python code:

import scipy.io.wavfile as wavfile
import numpy as np
import pylab as pl
import time
import os
import sys
import subprocess
from scipy import mean
from random import randint

# music wav file
FILE = “karaoke.wav”
rate, data = wavfile.read(FILE)
t_total = len(data[:,0])/rate
display_rate = 1500 #number of frames processed in one iteration
sample_size = 120
max_display = 90
data_length = len(data) #total number of frames
_min = min([abs(x) for x in data[:,0]]) #max amplitude in the wav
_max = max([abs(x) for x in data[:,0]]) #min amplitude in the wav

# IMPORTANT: correction factor. Change this value to match the song with equalizer
correction = 0.645

# cake settings
cols = int(subprocess.Popen(“tput cols”,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).stdout.readlines()[0]) #columns in terminal
display_char = “8”
cake_size = 50

# flame control
flame_flutter_rate = 50
FLAMES = [ ” . “, “. “, ” .” ]
current_flame = “”

os.system(“tput civis”) #hide cursor

# TODO open file with some player. If you are on mac, uncomment following line
#os.system(“open “+FILE)

for _f in range(data_length/display_rate):

# fluttering effect to candle flames
if _f%flame_flutter_rate == 0:
current_flame = (” “*(cols/2 – cake_size/2))+((” “+FLAMES[randint(0,2)]+” “)*(cake_size/5))
print current_flame

# candles
print (” “*(cols/2 – cake_size/2))+(” | “*(cake_size/5))
# cake top layer
print (” “*(cols/2 – cake_size/2))+(“-“*cake_size)

bucket = []
mug = []
# mug contains the current frame samples (absolute values) of given sample_size
# average of mugs are put into bucket
for value in data[:,0][_f*display_rate+1:(_f+1)*display_rate]:
mug.append(abs(value))
if len(mug) == sample_size:
bucket.append(mean(mug))
mug = []
bucket = [ (float)((x – _min) * max_display)/(_max – _min) for x in bucket ]

# print the equalizer from the bucket
for value in bucket:
print (” “*(cols/2 – cake_size/2))+”| “+(“8″*(value%(cake_size-2)))+(” “*(cake_size-value-2))+”|”

# bottom crust of the cake
print (” “*(cols/2 – cake_size/2))+(“-“*cake_size)

# print happy birthday message
os.system(“figlet -c -f small Happy Birthday qwerty!”)

# sleep to match with the audio
“””
NOTE: correction has to be multiplied to sleep time
This is because of several factors like time taken to wake from sleep, type of terminal used..etc
CHANGE THE VALUE OF correction TO FIT YOUR NEED
“””
time.sleep(((float)(display_rate * t_total) / data_length)*correction)

# clear screen
if _f != data_length/display_rate-1:
os.system(“clear”)

raw_input()

Problem: you’re calling a function that returns a list of results when you know that there’s only one result. It will be a singleton list, but you don’t want to bother with that— you just want the value of the one item.

Pedestrian solution: put a [0] at the end of the expression:

result = getResults()[0]

Slick solution: put a comma (,) at the end of the variable:

result, = getResults()

Why does this work? The trailing comma turns the variable into a single-element tuple. When you assign to a tuple, Python unpacks whatever is on the right-hand side into each element of the tuple. (You’ve probably seen

x, y = first(), second()

or something like that.) In this case, it unpacks the only item. If the function actually returns 0 or more than 1 result, you’ll get a ValueError (“need more than 0 values to unpack” or “too many values to unpack”). If you had used the pedestrian method with the square brackets, you’d get an IndexError.

I find that I need to unpack things quite often, and it’s good to have little idioms like this to remind yourself of your assumptions. (In this case, the comma indicates that you expect exactly one result; a [0] would suggest that you expect at least one result.)

“import this”
output of this is Perhaps the best-known and most-quoted passage of Python philosophy by Tim Peters, a longtime Python guru who wrote down many of the principles that guide Python’s own development process. The 19 lines he came up with, called the Zen of Python, have been so influential to Python programmers over time that they are immortalized as Python Enhancement Proposal (PEP) 201 and in the Python distribution itself, as an “Easter egg” module called this

The following tricks I find pretty useful in my daily Python work. I also added a few I stumbled upon lately.

1. Use collections

This really makes your code more elegant and less verbose, a few examples I absorbed this week:

Named tuples:

>>> Point = collections.namedtuple(‘Point’, [‘x’, ‘y’])
>>> p = Point(x=1.0, y=2.0)
>>> p
Point(x=1.0, y=2.0)

Now you can index by keyword, much nicer than offset into tuple by number (less readable)

>>> px
1.0
>>> py

Elegantly used when looping through a csv:

with open(‘stock.csv’) as f:
f_csv = csv.reader(f)
headings = next(f_csv)
Row = namedtuple(‘Row’, headings)
for r in f_csv:
row = Row(*r) # note the star extraction
# … process row …

I like the unpacking star feature to throw away useless fields:

line = ‘nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false’
>>> uname, *fields, homedir, sh = line.split(‘:’)
>>> uname
‘nobody’
>>> homedir
‘/var/empty’
>>> sh
‘/usr/bin/false’

Superconvenient: the defaultdict:

from collections import defaultdict
rows_by_date = defaultdict(list)
for row in rows:
rows_by_date[row[‘date’]].append(row)”,

Before I would init the list each time which leads to needless code:

if row[‘date’] not in rows_by_date:

rows_by_date[row[‘date’]] = []

You can use OrderedDict to leave the order of inserted keys:

>>> import collections
>>> d = collections.OrderedDict()
>>> d[‘a’] = ‘A’
>>> d[‘b’] = ‘B’
>>> d[‘c’] = ‘C’
>>> d[‘d’] = ‘D’
>>> d[‘e’] = ‘E’
>>> for k, v in d.items():
… print k, v

a A
b B
c C
d D
e E

Another nice one is Counter:

from collections import Counter

words = [
‘look’, ‘into’, ‘my’, ‘eyes’, ‘look’, ‘into’, ‘my’, ‘eyes’,
‘the’, ‘eyes’, ‘the’, ‘eyes’, ‘the’, ‘eyes’, ‘not’, ‘around’, ‘the’,
‘eyes’, “”don’t””, ‘look’, ‘around’, ‘the’, ‘eyes’, ‘look’, ‘into’,
‘my’, ‘eyes’, “”you’re””, ‘under’
]
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [(‘eyes’, 8), (‘the’, 5), (‘look’, 4)]”,

Again, before I would write most_common manually. Not necessary, this is all done already somewhere in the stdlib 🙂

2. sorted() accepts a key arg which you can use to sort on something else

Here for example we sort on surname:

>>> sorted(names, key=lambda name: name.split()[-1].lower())
[‘Ned Batchelder’, ‘David Beazley’, ‘Raymond Hettinger’, ‘Brian Jones’]

3. Create XMl from dict

Creating XML tags manually is usually a bad idea, I bookmarked this simple dict_to_xml helper:

from xml.etree.ElementTree import Element
def dict_to_xml(tag, d):
”’
Turn a simple dict of key/value pairs into XML
”’
elem = Element(tag)
for key, val in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem”

4. Oneliner to see if there are any python files in a particular directory

Sometimes ‘ any ‘ is pretty useful:

import os
files = os.listdir(‘dirname’)
if any(name.endswith(‘.py’) for name in files):
5. Use set operations to match common items in lists
>>> a = [1, 2, 3, ‘a’]
>>> b = [‘a’, ‘b’, ‘c’, 3, 4, 5]
>>> set(a).intersection(b)
{3, ‘a’}

6. Use re.compile

If you are going to check a regular expression in a loop, don’t do this:

for i in longlist:
if re.match(r’^…’, i)
yet define the regex once and use the pattern:
p = re.compile(r’^…’)
for i in longlist:
if p.match(i)

7. Printing files with potential bad (Unicode) characters

The book suggested to print filenames of unknown origin, use this convention to avoid errors:

def bad_filename(filename):
return repr(filename)[1:-1]
try:
print(filename)
except UnicodeEncodeError:
print(bad_filename(filename))

Handling unicode chars in files can be nasty because they can blow up your script. However the logic behind it is not that hard to grasp. A good snippet to bookmark is the encoding / decoding of Unicode:

>>> a
‘pýtĥöñ is awesome\n’
>>> b = unicodedata.normalize(‘NFD’, a)
>>> b.encode(‘ascii’, ‘ignore’).decode(‘ascii’)
‘python is awesome\n’

O’Reilly has a course on Working with Unicode in Python .

8. Print is pretty cool (Python 3)

I am probably not the only one writing this kind of join operations:

>>> row = [“1”, “bob”, “developer”, “python”]
>>> print(‘,’.join(str(x) for x in row))
1,bob,developer,python

Turns out you can just write it like this:

>>> print(*row, sep=’,’)
1,bob,developer,python
Note again the * unpacking.

9. Functions like sum() accept generators / use the right variable type

I wrote this at a conference to earn me a coffee mug 😉

sum = 0
for i in range(1300):
if i % 3 == 0 or i % 5 == 0:
sum += i
print(sum)

Returns 394118, while handing it in I realized this could be written much shorter and efficiently:

>>> sum(i for i in range(1300) if i % 3 == 0 or i % 5 == 0)
394118

A generator:

lines = (line.strip() for line in f)

is more memory efficient than:

lines = [line.strip() for line in f] # loads whole list into memory at once

And concatenating strings is inefficient:

s = “line1\n”
s += “line2\n”
s += “line3\n”
print(s)

Better build up a list and join when printing:

lines = []
lines.append(“line1”)
lines.append(“line2”)
lines.append(“line3”)
print(“\n”.join(lines))
Another one I liked from the cookbook:
portfolio = [
{‘name’:’GOOG’, ‘shares’: 50},
{‘name’:’YHOO’, ‘shares’: 75},
{‘name’:’AOL’, ‘shares’: 20},
{‘name’:’SCOX’, ‘shares’: 65}
]
min_shares = min(s[‘shares’] for s in portfolio)

One line to get the min of a numeric value in a nested data structure.

10. Enumerate lines in for loop

You can number lines (or whatever you are looping over) and start with 1 (2nd arg), this is a nice debugging technique

for lineno, line in enumerate(lines, 1): # start counting at 0
fields = line.split()
try:
count = int(fields[1])

except ValueError as e:
print(‘Line {}: Parse error: {}’.format(lineno, e))

11. Pandas

Import pandas and numpy:

import pandas as pd
import numpy as np

12. Make random dataframe with three columns:

df = pd.DataFrame(np.random.rand(10,3), columns=list(‘ABC’))
Select:
# Boolean indexing (remember the parentheses)
df[(df.A < 0.5) & (df.B > 0.5)]
# Alternative, using query which depends on numexpr
df.query(‘A < 0.5 & B > 0.5′)
Project:
# One columns
df.A
# Multiple columns
# there may be another shorter way, but I don’t know it
df.loc[:,list(‘AB’)]

  • Often used snippets
  • fechas

13. Difference (in days) between two dates:

from datetime import date

d1 = date(2013,1,1)
d2 = date(2013,9,13)
abs(d2-d1).days
directory-of-script snippet
os.path.dirname(os.path.realpath(__file__))
# combine with
os.path.join(os.path.dirname(os.path.realpath(__file__)), ‘foo’,’bar’,’baz.txt’)

14. PostgreSQL-connect-query snippet

import psycopg2
conn = psycopg2.connect(“host=’localhost’ user=’xxx’ password=’yyy’ dbname=’zzz'”)
cur = conn.cursor()
cur.execute(“””SELECT * from foo;”””)
rows = cur.fetchall()
for row in rows:
print ” “, row[0]
conn.close()
Input parsing functions

15. Expand input-file args:

# input_data: eg ‘file.txt’ or ‘*.txt’ or ‘foo/file.txt’ ‘bar/file.txt’
filenames = [glob.glob(pathexpr) for pathexpr in input_data]
filenames = [item for sublist in filenames for item in sublist]

15. Parse key-value pair strings like ‘x=42.0,y=1’:

kvp = lambda elem,t,i: t(elem.split(‘=’)[i])
parse_kvp_str = lambda args : dict([(kvp(elem,str,0), kvp(elem,float,1)) for elem in args.split(‘,’)])
parse_kvp_str(‘x=42.0,y=1’)

Postgres database functions

16. Upper case in Python (just for example):

— create extension plpythonu;
CREATE OR REPLACE FUNCTION python_upper
(
input text
) RETURNS text AS
$$
return input.upper()
$$ LANGUAGE plpythonu STRICT;

17. Convert IP address from text to integer:

CREATE FUNCTION ip2int(input text) RETURNS integer
LANGUAGE plpythonu
AS $$
if ‘struct’ in SD:
struct = SD[‘struct’]
más:
import struct
SD[‘struct’] = struct
if ‘socket’ in SD:
socket = SD[‘socket’]
más:
import socket
SD[‘socket’] = socket
return struct.unpack(“!I”, socket.inet_aton(input))[0]
$$;
Convert IP address from integer to text:
CREATE FUNCTION int2ip(input integer) RETURNS text
LANGUAGE plpythonu
AS $$
if ‘struct’ in SD:
struct = SD[‘struct’]
más:
import struct
SD[‘struct’] = struct
if ‘socket’ in SD:
socket = SD[‘socket’]
más:
import socket
SD[‘socket’] = socket
return socket.inet_ntoa(struct.pack(“!I”, input))
$$;

18. Commandline options

optparse-commandline-options snippet
from optparse import OptionParser
usage = “usage: %prog [options] arg ”
parser = OptionParser(usage=usage)
parser.add_option(“-x”, “–some-option-x”, dest=”x”, default=42.0, type=”float”,
help=”a floating point option”)
(options, args) = parser.parse_args()
print options.x
print args[0]

19. print-in-place (progress bar) snippet

import time
import sys
for progress in range(100):
time.sleep(0.1)
sys.stdout.write(“Download progress: %d%% \r” % (progress) )
sys.stdout.flush()

Packaging snippets

20. poor-mans-python-executable trick

Learned this trick from voidspace . The trick uses two files (__main__.py and hashbang.txt):

__main__.py:
print ‘Hello world’
hashbang.txt (adding a newline after ‘python2.6’ is important):
#!/usr/bin/env python2.6
Build an “executable”:
zip main.zip __main__.py
cat hashbang.txt main.zip > hello
rm main.zip
chmod u+x hello
Run “executable”:
$ ./hello
Hello world

21. import-class-from-file trick

Import class MyClass from a module file (adapted from stackoverflow ):

import imp
mod = imp.load_source(‘name.of.module’, ‘path/to/module.py’)
obj = mod.MyClass()

22. Occusional-usage snippets

Extract words from string

words = lambda text: ”.join(c if c.isalnum() else ‘ ‘ for c in text).split()
words(‘Johnny.Appleseed!is:a*good&farmer’)
# [‘Johnny’, ‘Appleseed’, ‘is’, ‘a’, ‘good’, ‘farmer’]

23. IP address to integer and back

import struct
import socket
def ip2int(addr):
return struct.unpack(“!I”, socket.inet_aton(addr))[0]
def int2ip(addr):
return socket.inet_ntoa(struct.pack(“!I”, addr))

24. Fluent Python Interface

Copied from riaanvddool .

# Fluent Interface Definition
class sql:
class select:
def __init__(self, dbcolumn, context=None):
self.dbcolumn = dbcolumn
self.context = context
def select(self, dbcolumn):
return self.__class__(dbcolumn,self)
# Demo
q = sql.select(‘foo’).select(‘bar’)
print q.dbcolumn #bar
print q.context.dbcolumn #foo
Flatten a nested lists
def flatten(elems):
“””
[[‘a’], [‘b’,’c’,[‘d’],’e’,[‘f’,’g’]]]
“””
stack = [elems]
top = stack.pop()
while top:
head, tail = top[0], top[1:]
if tail: stack.append(tail)
if not isinstance(head, list): yield head
else: stack.append(head)
if stack: top = stack.pop()
else: break
snap rounding
EPSILON = 0.000001
snap_ceil = lambda x: math.ceil(x) if abs(x – round(x)) > EPSILON else round(x)
snap_floor = lambda x: math.floor(x) if abs(x – round(x)) > EPSILON else round(x)
merge-two-dictionaries snippet
x = {‘a’: 42}
y = {‘b’: 127}
z = dict(x.items() + y.items())
# z = {‘a’: 42, ‘b’: 127}

25. anonymous-object snippet

Adapted from stackoverflow :

class Anon(object):
def __new__(cls, **attrs):
result = object.__new__(cls)
result.__dict__ = attrs
return result

26. Alternative :

class Anon(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return self.__str__()
def __str__(self):
return “, “.join([“%s=%s” % (key,value) for key,value in self.__dict__.items()])

27. generate-random-word snippet

Function that returns a random word (could also use random.choicewith this list of words ):

import string, random
randword = lambda n: “”.join([random.choice(string.letters) for i in range(n)])
setdefault tricks
Increment (and initialize) value:
d = {}
d[2] = d.setdefault(2,39) + 1
d[2] = d.setdefault(2,39) + 1
d[2] = d.setdefault(2,39) + 1
d[2] # value is 42

29. Append value to (possibly uninitialized) list stored under a key in dictionary:

d = {}
d.setdefault(2, []).append(42)
d.setdefault(2, []).append(127)
d[2] # value is [42, 127]

Binary tricks

30. add-integers-using-XOR snippet

Swap two integer variables using the XOR swap algorithm :

x = 42
y = 127
x = x ^ y
y = y ^ x
x = x ^ y
x # value is 127
y # value is 42

I know that most of it has been mentioned already But I think you should find some new tricks as well.

Greetings,

Python is a gem of a language for developers owing to the ease of programming, and the enormous set of libraries that are available. I shall list some very useful modules, and some tips which can be adopted while coding.

  • Use the ipython shell for interactive programming. It is much better than the traditional python shell, and is easier to code in.

sudo pip install ipython

  • In Python there’s a module called pickle . It can be used to preserve data structures, in their format, and load them as simply.

Al aire libre

Al aire libre

Using this, you can store any kind of data structure while executing one module, and later revive it in another module. No hassle of storing in a text file, string processing and so on!

  • Need to share a file with a friend? Sin preocupaciones. If you are connected to the internet, enter into the directory where the files reside, and host them using python http server.

Al aire libre

Then share your IP address with your friend, and he/she can access those files by opening your ‘IP address:8000’ on his browser, and download the files!

  • Use list comprehensions to write 5 lines worth of code in a single line!

a.txt :
Al aire libre

Now one can apply list comprehension like this :
Al aire libre

  • When searching for a key in a dictionary,

if i in dict_var.keys():
print dict_var[i]

if i in dict_var:
print dict_var[i]

Edit : An even more efficient method would be to use a try catch block surrounding the dictionary lookup. This is because, try-catch is more efficient compared to if comparison.
try:
print dict_var[i]
except KeyError:
pasar

The third method is preferred, because the first generates a list and returns it, which consumes a lot of time, whereas, the second method simply does a dictionary lookup. And, try catch makes it even more efficient.

I shall add more if and when I remember 🙂

list comprehensions

[# list comprehensions
# In-line anonymous list comprehensions functions

# sum
nl = [2, 3, 6, 18]
[j for j in [0] for i in nl for j in [j + i]][-1]

# product
[j for j in [1] for i in nl for j in [j * i]][-1]

# factorial
fac = 3
[j for j in [1] for i in range(2, fac+1) for j in [j*i]][-1]

# with prefix functions

T= [set(s) for s in [(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7),(4,5,6,7,8)]]

f= set.intersection
[ s for s in [f(*T[:2])] for i in range(2,len(T)) for s in [f(s,T[i])] ][-1]
set([4, 5] ) ## issues the null set if no intersection between all given sets

f= set.union
[ s for s in [f(*T[:2])] for i in range(2,len(T)) for s in [f(s,T[i])] ][-1]
set([1, 2, 3, 4, 5, 6, 7, 8])

# join
T= [(1,2,3,4,5,6,7),(3,4,5,6,7),(5,6,7),(7,8,9,2,1,5)]
[ s for s in [T[0]] for i in range(1,len(T)) for s in [s + T[i]] ][-1]
(1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 5, 6, 7, 7, 8, 9, 2, 1, 5)

T= [“abcd”,”efgh”,”ijkl”,”mnop”,”qrst”]
[ s for s in [T[0]] for i in range(1,len(T)) for s in [s + T[i]] ][-1]
‘abcdefghijklmnopqrst’

# with predicates

l= [20,30,40,50,60,70,80,90,1,2,3,4,5]

# “all” function
[ p for p in [l[0]>42] for i in range(1,len(l)) for p in [p and l[i]>42] ][-1]
Falso

# “any” function
[ p for p in [l[0]>42] for i in range(1,len(l)) for p in [p or l[i]>42] ][-1]
Cierto
# Also I work a lot with strings but don’t like quoting everything

# dictionary comprehensions
ls= “one ten two twenty three thirty four forty five fifty”.split()

{ ls[i]: ls[i+1] for i in range(0,len(ls),2) }
{‘four’: ‘forty’, ‘three’: ‘thirty’, ‘five’: ‘fifty’, ‘two’: ‘twenty’, ‘one’: ‘ten’}

ls1=’one two three four five six seven eight nine ten’
ls2=’aa1 ab2 ac3 ad4 ae5 af6 ag7 ag8 ah9 ai0′

{ l1:l2 for l1,l2 in zip(ls1.split(), ls2.split()) }
{‘seven’: ‘ag7’, ‘ten’: ‘ai0’, ‘nine’: ‘ah9’, ‘six’: ‘af6’, ‘three’: ‘ac3’,
‘two’: ‘ab2’, ‘four’: ‘ad4’, ‘five’: ‘ae5’, ‘eight’: ‘ag8’, ‘one’: ‘aa1’}