python - Python迭代N嵌套for循环?
问题描述
我有一个包含 N 个键列的 CSV 文件,以及一个包含对 1 到 N 个键列的引用的表达式的列,我想用该行的每个键列中的值替换它们。希望下面的例子能阐明我的意思。
下面的关键列是 A、B、C
期望的输出:
20_A
20_B
30_A
30_B
40_C_4
40_C_5
我的解决方案:
keys = ['Age','Type','Delay']
df = pd.read_csv(csv_path)
for index, row in df.iterrows():
key1_list = row[keys[0]].split(",")
key2_list = row[keys[1]].split(",")
key3_list = row[keys[2]].split(",")
expression = row['Expression']
# Iterate over all combinations of key column values and export a chart for each one
for KEY1 in key1_list:
for KEY2 in key2_list:
for KEY3 in key3_list:
string = expression
string = string.replace("<" + keys[0] + ">", KEY1)
string = string.replace("<" + keys[1] + ">", KEY2)
string = string.replace("<" + keys[2] + ">", KEY3)
print(string)
但是,我想将我的代码概括为适用于任意数量的键列,并且只需要在开始时更新键列表。这将需要循环到深度 len(keys)。但是我不知道如何使用平面代码将循环推广到任何深度,我查看了 itertools 但找不到我需要的东西。我认为递归可能有效,但我更愿意避免这种情况。
解决方案
itertools
递归当然可以为您解决问题,但在走这条路之前,您应该再看看。您想要的是您的密钥的产品,以生成所有可能的密钥组合。
实现此目的的一种方法如下:
import pandas as pd
import itertools
csv_path = "path/to/file"
df = pd.read_csv(csv_path)
# Find available keys from data frame instead of manually input it:
keys = list(df.keys()[:-1]) # Do not include "Expression" as it is not a key.
for index, row in df.iterrows():
# Add list of keys to a list of lists
# (The order needs to be preserved, therefore avoiding dict)
key_list = []
for key in keys:
# The code uses ',' as value separator in each cell.
# Does this work in a csv file?
key_list.append(list(row[key].split(',')))
expression = row['Expression']
# All key combinations are then generated with 'itertools.product'
combos = itertools.product(*key_list)
# Each combo is then handled separately
for combo in combos:
string = expression
# Replace each key in order
# Must be done sequentially since depth is not known/variable
for key, value in zip(keys, combo):
string = string.replace('<' + key + '>', value)
print(string)
希望这段代码是可以理解的,可以做你想做的。否则,请告诉我,我会尝试进一步澄清。
推荐阅读
- ios - IOS/swift currentTitle 返回 nil
- python - TypeError:参数无效,不是字符串或列:
在 0x7f1f357c6160> 类型 - python - Jinja 模板 groupby 排序问题
- python - Python htpasswd 设置 zipfiles 并删除
- flutter - 颤振在调试模式下运行错误未来
_loadAsync(? - javascript - Angular 循环依赖:处理它的最佳实践
- javascript - 尝试发送嵌入时抛出错误
- reactjs - 反应路由器 useHistory 未定义
- c++ - 数据类型声明比分配的大小
- php - 这只发生在实时服务器上:致命错误:未捕获的错误:在布尔输入上调用成员函数 signin()