这取决于您是想要一个包含整个 user_kw_list 的长文件名,还是要为列表中的每个关键字保存一个文件。
无论哪种情况,f-strings 都值得研究。如果你的 Python 版本支持的话,相比 format 方法,它非常简洁,并且优化得很好。阅读更多关于 f-strings here.
如果你想要一个长文件名,你需要join这些项目一起。在这种情况下,您几乎可以肯定不需要列表推导。这是一种可能的解决方案:
user_kw_list = ['ray ban','abaco sunglasses']
joined = ('_or_').join(user_kw_list).replace(' ', '_')
# .replace(' ', '_') is optional. It maintains the snake_case naming convention.
path = f"./data/{joined}_interest_over_time.csv"
# This is functionally similar to: "./data/{}_interest_over_time.csv".format(joined)
interest_over_time_df.to_csv(path, index=True)
# This will save the file as ./data/ray_ban_or_abaco_sunglasses_interest_over_time.csv
# Note: Very long filenames can sometimes cause problems on some operating systems.
相反,如果您想为列表中的每个关键字保存一个文件,问题是您的循环包含在方法调用中。应该反过来,for 循环封装了to_csv 方法。
对于这个用例,传统的 for 循环可能更具可读性,因为您正在运行带有副作用的代码,而不是返回一个变量。
一个解决方案如下所示:
user_kw_list = ['ray ban','abaco sunglasses']
for kw in user_kw_list:
kw = kw.replace(' ', '_')
# As before, this line is optional. It maintains the snake_case convention.
path = f"./data/{kw}_interest_over_time.csv"
# This is functionally similar to: "./data/{}_interest_over_time.csv".format(kw)
interest_over_time_df.to_csv(path, index=True)
# This will save two files: ray_ban_interest_over_time.csv
# and abaco_sunglasses_interest_over_time.csv
如果第二种情况需要是列表推导式,则如下所示:
[interest_over_time_df.to_csv(f"./data/{kw}_interest_over_time.csv", index=True) for kw in user_kw_list]