Python:按索引列出的列表中的pop项

时间:2016-04-21 07:01:39

标签: python list

我必须通过索引删除行列表中的项lines[0]不在标题中。

输入如下:

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

预期输出如下:

lines = [['default_code'],[1212],[45]]

到目前为止,我试图做的是:

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

这没有产生所需的输出。请帮助解决这个问题。

5 个答案:

答案 0 :(得分:1)

我根据您的代码进行更正:

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

输出:

[['default_code'], [1212], [45]]

答案 1 :(得分:0)

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

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

输出:

[['default_code', 'fld_code']]

如果您想要的是“手动”循环,请使用list.remove

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

答案 2 :(得分:0)

如果你想使用pop,你必须使用索引,然后最好从头开始没有indice问题。

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

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

答案 3 :(得分:0)

这是你想写的代码:)

for x in lines[0]:
    if x not in headers:
        n = lines[0].index(x)
        for line in lines:
            line.remove(line[n])
print lines
你很亲密。你不想使用pop,如果你想删除'某个位置的元素。有更优雅和更短的解决方案,但这适合您的编码风格。看看python中的list comprehension,它非常强大。

答案 4 :(得分:0)

    for line in lines[0]:
        line.pop(line.index(x))

我希望循环线保持字符串类型的值。我们不能使用pop with string。如果我错了,请纠正我。

相关问题