Python:按索引在列表列表中弹出项

2024-04-25 22:23:15 发布

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

我必须根据不在标题中的lines[0]的索引删除行列表中的一个项。在

输入如下:

headers = ['internal_id', 'default_code', 'ean13', 'supplier_id', 'product_qty']
lines = [['default_code', 'fld_code', 'test'],[1212, 4545, 'test1'],[45, 787, 'test2']]

预计产量如下:

^{pr2}$

到目前为止,我一直在努力:

for x in lines[0]:
    if x not in headers:
        for line in lines[0]:
            line.pop(line.index(x))
print lines

这没有产生所需的输出。请帮忙。在


Tags: iniddefault标题列表forlinecode
3条回答

如果你想使用pop,你必须使用索引,那么最好是从末尾开始,这样就没有索引问题。在

for x in range(len(lines)-1,-1,-1):
    if lines[x][0] not in headers:
        lines.pop(x)     
print lines

我不知道你的项目是什么,但你应该考虑使用措辞。在

我根据你的代码更正:

for i, x in reversed(list(enumerate(lines[0]))):
    if x not in headers:
        for line in lines:
            line.pop(i)
print lines

输出:

^{pr2}$

使用列表理解(也可以使用filter)。在

lines = [line for line in lines if line[0] in headers]

输出:

^{pr2}$

如果需要“手动”循环,请使用^{}

for x in lines:
    if x[0] not in headers:
        lines.remove(x)

相关问题 更多 >