ComenzarEmpieza gratis

List comprehension

List comprehensions are a concise and convenient way to address a common programming task: iterating through a list, making a calculation, and saving the calculation into a new list. While this can be performed using a for loop, a list comprehension preforms the same task with fewer number of lines.

The following list comprehension squares all values in a list:

x = [1, 2, 3, 4]
print([i**2 for i in x])

[1, 4, 9, 16]

A list of file names has been provided to you in the inflam_files list. Your task is to write a list comprehension that imports these files as pandas DataFrames in a single list.

Este ejercicio forma parte del curso

Python for R Users

Ver curso

Instrucciones del ejercicio

  • Re-write the provided for loop as a list comprehension: dfs_comp.

Ejercicio interactivo práctico

Prueba este ejercicio completando el código de muestra.

# Append dataframes into list with for loop
dfs_list = []
for f in inflam_files:
    dat = pd.read_csv(f)
    dfs_list.append(dat)

# Re-write the provided for loop as a list comprehension: dfs_comp
dfs_comp = [____.____(____) for ____ in ____]
print(dfs_comp)
Editar y ejecutar código