如何在列表理解中与其他操作一起使用print()? [英] How to use print() along with other operations in list comprehension?

查看:57
本文介绍了如何在列表理解中与其他操作一起使用print()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV数据文件目录,并使用列表理解语句中的pandas.read_csv()将所有这些文件加载​​到一行中.

I have a directory of CSV data files and I load all of them in one line using pandas.read_csv() within a list comprehension statement.

import glob
import pandas as pd
file_list = glob.glob('../data/')
df_list = [pd.read_csv(f) for f in file_list]
df = pd.concat(df_list, ignore_index=True)

现在,我想在每次加载数据文件时打印文件路径,但是我找不到在列表理解中使用多个语句的方法.例如,类似[pd.read_csv(f); print(f) for f in file_list]的东西会导致SyntaxError.

Now I want to print the file path every time when it loads a data file, but I cannot find a way to use multiple statements in list comprehension. For example, something like [pd.read_csv(f); print(f) for f in file_list] will cause a SyntaxError.

我能得到的最接近的结果是让print()在if语句中返回None,该语句在打印后像pass一样工作.

The closest thing I can get is to let print() to return None in an if-statement, which works like a pass after printing.

df_list = [pd.read_csv(f) for f in file_list if print(f) is None]

是否有适当的方法来做到这一点?我喜欢列表理解的简洁性,但似乎不允许多条语句.

Is there a proper way of doing this? I like list comprehension for its conciseness, but it does not seem to allow multiple statements.

推荐答案

如果您想要列表理解(鉴于for循环的速度提高,这是可以理解的),则可以稍微修改您的解决方案,因为None是虚假的:

If you want a list comprehension (understandable given the speed improvement over a for loop), you could slightly modify your solution because None is falsy:

df_list = [pd.read_csv(f) for f in file_list if not print(f)]

或者做一个起作用的函数:

Alternatively make a function that does the work:

def read_and_print(f):
    print(f)
    return pd.read_csv(f)

df_list = [read_and_print(f) for f in file_list]

但是,这些方法违反了Python通常遵循的命令-查询"分离原理,因为该函数同时具有副作用和感兴趣的return值.尽管如此,我认为这些操作还是很实用的,特别是如果您想现在print()查看数据,但是以后您打算删除print()调用.

However, the approaches violate the Command–query separation principle that Python generally follows because the function has both a side-effect and a return value of interest. Nonetheless, I think these are quite pragmatic, particularly if you want to print() now to view the data, but later you plan to remove the print() calls.

这篇关于如何在列表理解中与其他操作一起使用print()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆