简体   繁体   English

是否可以在Python列表理解中编写多个语句?

[英]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. 我正在尝试将HTML表读入pandas,然后打印并将DataFrame附加到列表中。 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. 话虽如此,我不建议您这样做,而应该使用@alexce的答案。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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