将列表项用作列表理解中的值

2024-04-25 11:58:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一份清单:

com = ['eto', 'eti', 'etn', 'ets', 'eot', 'eoi', 'eon', 'eos', 'eit', 'eio', 'ein']

然后在程序中,我需要对每个单元格中的每个字符执行3种不同的计算。你知道吗

newC = [w.replace(mCommon[0], com[e]) for w in newC]
newC = [w.replace(mCommon[0], com[t]) for w in newC]
newC = [w.replace(mCommon[0], com[o]) for w in newC]

下一次是的

newC = [w.replace(mCommon[0], com[e]) for w in newC]
newC = [w.replace(mCommon[0], com[t]) for w in newC]
newC = [w.replace(mCommon[0], com[i]) for w in newC]

以此类推,在循环中,所以我不硬编码那些字符,它们应该从列表中获取。你知道吗

从本质上说,我希望这三种列表理解在每个组合中循环,例如第一次分别使用“e”、“t”和“o”,然后分别使用“e”、“t”和“I”,依此类推。你知道吗

我现在得到的是索引超出范围,原因很明显。而且m部分也不正确,因为它没有改变。你知道吗


Tags: incom列表for字符replaceetieto
2条回答

如果您想要一个函数:

newC = [w.replace(mCommon[0], 'e') for w in newC]
newC = [w.replace(mCommon[0], 't') for w in newC]
newC = [w.replace(mCommon[0], 'o') for w in newC]

在第一次通话中:

newC = [w.replace(mCommon[0], 'e') for w in newC]
newC = [w.replace(mCommon[0], 't') for w in newC]
newC = [w.replace(mCommon[0], 'i') for w in newC]

在第二次通话中,你可以写:

com = ['eto', 'eti', 'etn', 'ets', 'eot', 'eoi', 'eon', 'eos', 'eit', 'eio', 'ein']
g_com_index = 0

def adapt_c(newC):
    global g_com_index
    for c in com[g_com_index % len(com)]
        newC = [w.replace(mCommon[0], c) for w in newC]
    g_com_index += 1

    return newC

你不必写三个单子。循环遍历list,然后循环遍历每个字符,将其中的每个字符用作replace参数。你知道吗

for element in list: #element in be 'eto', then 'eti' ...
    for character in element: # character will be 'e','t','i' then 'e','t','o'...
        newC = [w.replace(mCommon[0], character) for w in newC]

需要注意的是,上面的代码假定newC已经存在于代码中的某个地方。你知道吗

相关问题 更多 >

    热门问题