简体   繁体   中英

Is it possible to write multiple statements in Python list comprehension?

I am trying to read an HTML table into pandas and then print and also append the DataFrames to a list as well. Something like:

dfs = pd.read_html(str(table))
[print(df),records_list.append(df), for df in dfs]

It is possible, but its not really pretty:

inputs = ['a', 'b', 'c']

mylist = [print(i) or i for i in inputs]

print(mylist)

This abuses the fact that the print function returns None all the time. The result is:

a
b
c
['a', 'b', 'c']

That being said, I would NOT recommend to do this and rather go with @alexce's answer.

Not directly, you would either need to expand it to a regular loop:

for df in dfs:
    print(df)
    records_list.append(df)

Or, you could even create a custom function where you would print and return:

def print_and_return(item): 
    print(item)
    return item

records_list = [print_and_return(df) for df in dfs]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM