0

我有一个需要插入特定字符的列表\n

但是,同时这将在两个 for 循环内。在这种情况下,我们需要检查\n该位置是否已经存在。

如果存在,请不要插入,否则\n在该位置插入。

# position of '\n' from previous list
# '\n' needs to be exactly at the same position as in the previous lsit

indexes = [i for i, val in enumerate(input_list) if val == '\n']

ncol = some value

nrows = some value

for column in range(1, ncol):

    for row in range(1, nrows):
        abc.append(ws2.cell(row = row, column=column).value)
        if ind in indexes:
            abc.insert(ind, '\n')
        #print('abc: ', abc)
        concatABC = '\n'.join(abc)
        #print('Concate: ', concatABC)
        ws.cell(row=(nrows), column=(column)).value = concatABC
    del abc[:]

if循环中,我必须检查是否\n已经存在。每次都插入它是没有意义的,因为它只需要一次。

我正在使用输入 TXT 文件生成的 input_list 中给出的特定数据结构生成 excel 文件。

对困惑感到抱歉,

ind 的值来自列表索引,我从原始输入列表中获取 '\n' 的位置。在我的代码之间,我从 xml 文件中提取数据并将其放入 Excel。现在,在最后一个 Excel 行/单元格中连接这些数据时,我需要保持 TXT 文件中给定的格式。

我的问题是只有输入列表是稳定的,所有其他的东西要么来自 XML,要么在循环迭代时更新。

@wim:输入将是.. input_list = ['abc', '\n', 'def', 'ghi', '\n', 'jkl', 'mno']

我们从这个输入列表中获得 \n 的索引,然后在我的 excel 中,我连接所有顶行并将 \n 准确地放在输入列表中的位置。这就是全部。

Excel 中的输出:

第 1 行:ABC

第 2 行:定义

第 3 行:ghi

第 4 行:jkl

第 5 行:mno

第 6 行:abc
空行 (\n)
def
ghi
空行 (\n)
jkl
mno

4

1 回答 1

1

你可以使用这样的函数:

lis=[1,2,3,4,5,'\n','abc','a']

def ins(pos):

    if lis[pos]=='\n':
        print ('found')
    else:
        lis.insert(pos,'\n')

输出:

>>> ins(3)
>>> lis
[1, 2, 3, '\n', 4, 5, '\n', 'abc', 'a']
>>> ins(5)
>>> lis
[1, 2, 3, '\n', 4, '\n', 5, '\n', 'abc', 'a']
>>> ins(7)
found
>>> lis
[1, 2, 3, '\n', 4, '\n', 5, '\n', 'abc', 'a']
>>> ins(len(lis)-1)
>>> lis
[1, 2, 3, '\n', 4, '\n', 5, '\n', 'abc', '\n', 'a']
于 2012-08-13T11:19:35.020 回答