[英]How to iterate over a list of suffixes to add to the end of each variable in a list?
What I'm trying to do is optimize my current code that uses dataframes.我想要做的是优化我当前使用数据帧的代码。 The dataframes follow a similar naming convention, so instead of explicitly naming them, I'm trying to create them on the fly and then process them.数据帧遵循类似的命名约定,因此我没有明确命名它们,而是尝试动态创建它们然后处理它们。
days = [1, 2, 3, 4, 5]
#1,2,3,4,5 are dataframes
endings = ['_operation1', '_operation2']
suffixedFrames = [x.add_suffix(y) for x, y in zip(days, endings)]
print(suffixedFrames)
The problem is that when I run this, it only prints out two dataframes, specifically, 1_operation1 and 1_operation2.问题是当我运行它时,它只打印出两个数据帧,特别是 1_operation1 和 1_operation2。 How do I make it add the suffix to every dataframe in list days?如何让它在列表日内为每个数据帧添加后缀?
Zip does not work as you want to, but it creates an iterator of tuples, where the i-th tuple contains the i-th element of the 2 list you're using, as you can see in the documentation . Zip 无法按您的意愿工作,但它会创建一个元组迭代器,其中第 i 个元组包含您正在使用的 2 列表的第 i 个元素,如您在文档中所见。 In your case if you do print(list(zip(days, endings)))
you will see this:在你的情况下,如果你做print(list(zip(days, endings)))
你会看到这个:
[(1, '_operation1'), (2, '_operation2')]
. [(1, '_operation1'), (2, '_operation2')]
。
In order to achieve what you want you can do as follows:为了实现您想要的,您可以执行以下操作:
import itertools
days = [1, 2, 3, 4, 5]
#1,2,3,4,5 are dataframes
endings = ['_operation1', '_operation2']
suffixedFrames = [x.add_suffix(y) for x, y in list(itertools.product(days, endings))]
print(suffixedFrames)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.