gpt4 book ai didi

Python 迭代 N 嵌套 for 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:11 25 4
gpt4 key购买 nike

我有一个包含 N 个键列的 CSV 文件,以及一个包含对 1 到 N 个键列的引用的表达式的列,我想用该行的每个键列中的值替换这些键列。希望下面的例子能阐明我的意思。

下面的关键列是 A、B、C

Table

期望的输出:

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。您想要的是 key 的乘积,以生成所有可能的 key 组合。

实现此目的的一种方法如下:

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)

希望这段代码是可以理解的,并且可以按照您的意愿行事。否则请告诉我,我会尝试进一步澄清。

关于Python 迭代 N 嵌套 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com