List Comprenhensions — 9:41 min
9:41 min | Última modificación: Octubre 5, 2021
[1]:
#
# Llenado de una lista con append
#
squares = []
for x in range(10):
squares.append(x ** 2)
squares
[1]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[2]:
#
# Comprenhension equivalente
#
squares = [x ** 2 for x in range(10)]
squares
[2]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[3]:
#
# Código equivalente usando map()
#
squares = list(map(lambda x: x ** 2, range(10)))
squares
[3]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[4]:
#
# Creación de pares usando ciclos for anidados
#
combs = []
for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
combs.append((x, y))
combs
[4]:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[5]:
#
# Código equivalente usando un comprenhension
#
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
[5]:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[6]:
#
# Creación de una lista de listas
#
[list(range(5)) for _ in range(5)]
[6]:
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
[7]:
#
# iteracción sobre strings -- MAL
#
nums = ""
for n in range(20):
nums += str(n)
print(nums)
012345678910111213141516171819
[8]:
#
# Iteración sobre strings -- BIEN
#
nums = []
for n in range(20):
nums.append(str(n))
print("".join(nums))
012345678910111213141516171819
[9]:
#
# iteración sobre strings -- MEJOR
#
nums = [str(n) for n in range(20)]
"".join(nums)
[9]:
'012345678910111213141516171819'
[10]:
#
# Condicionales. if-then
#
[x for x in range(10) if x < 5]
[10]:
[0, 1, 2, 3, 4]
[11]:
#
# Condicionales. if-else
#
[x if x < 5 else 0 for x in range(10)]
[11]:
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
[12]:
#
# Dict comprenhension
#
{letter: i_letter for i_letter, letter in enumerate(["A", "B", "C", "D"])}
[12]:
{'A': 0, 'B': 1, 'C': 2, 'D': 3}
[13]:
#
# Construcción de un generador usando una comprenhension
# =============================================================================
# Numeros del 1 al 20 que contienen un '1'
#
import re
[str(x) for x in range(1, 21) if re.search("1", str(x))]
[13]:
['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19']
[14]:
generador = (i ** 2 for i in range(10))
for element in generador:
print(element)
0
1
4
9
16
25
36
49
64
81
[15]:
generador = (i ** 2 for i in range(10))
display(
next(generador),
next(generador),
)
0
1
[16]:
#
# Uso de generadores en funciones
# =============================================================================
#
def num_sequence(n):
counter = 0
while counter < n:
yield counter
counter += 1
for value in num_sequence(5):
print(value)
0
1
2
3
4
[17]:
#
# Uso de generadores para leer datos
# =============================================================================
#
data_url = "https://raw.githubusercontent.com/jdvelasq/datalabs/master/datasets/world_bank_development_Indicators.csv"
!wget --quiet {data_url} -P /tmp/
def read_large_file(file_object):
while True:
data = file_object.readline()
if not data:
break
yield data
with open("/tmp/world_bank_development_Indicators.csv", "r") as file:
gen_file = read_large_file(file)
print(next(gen_file), end="")
print(next(gen_file), end="")
print(next(gen_file), end="")
CountryName,CountryCode,Year,Total Population,Urban population (% of total)
Arab World,ARB,1960,92495902.0,31.285384211605397
Caribbean small states,CSS,1960,4190810.0,31.5974898513652