简体   繁体   English

如何迭代后缀列表以添加到列表中每个变量的末尾?

[英]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.

相关问题 Python:如何遍历列表列表,同时遍历每个嵌套列表中的每个项目 - Python: how to iterate over list of list while iterating over each item in each nested list Python:如何遍历词典列表并将每个词典作为值添加到具有唯一键的新词典中-无需重复 - Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats 如何遍历字符串,对于每个字母,如果它在字典(键)中,则将值添加到新列表中? - How to iterate over a string and for each letter, if it is in a dictionary (key), add values to a new list? 如何在列表的每个元素的末尾添加一个单词? - How to add a word at the end of each element of a list? 如何在列表中每个元素的末尾添加字符 - How to add characters at the end of each element in a list 如何在将列表中的每个值传递到 API 并在每个列表列表后暂停时迭代列表列表? - How to iterate over list of lists while passing each value in the lists into API and pausing after each list of list? 如何遍历列表中的每个名称以供用户输入? - How to iterate over each name in a list for user input? 如何在 pandas 中的字符串列表中的每个字符串上迭代代码 - How to iterate code over each string in a list of strings in pandas 对于字符串列表,如何遍历字符串字符的每个 position? - How to iterate over each position of a character of a string, for a list of strings? 如何迭代重复Python中每个元素的列表 - How to iterate over a list repeating each element in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM