在python 2中删除带有条件的列表列表

时间:2019-05-17 15:06:40

标签: python python-2.7

我正在python中使用“ for” ,如果满足某些条件,我需要删除一些T列表。

T=[[0, 2, 4, 6], [0, 2, 4, 8], [0, 2, 5, 8], [0, 2, 5, 11], [0, 2, 6, 11], [0, 3, 5, 8], [0, 3, 5, 11], [0, 3, 6, 10], [0, 3, 6, 11], [0, 3, 8, 10], [0, 4, 6, 10], [0, 4, 8, 10], [1, 3, 5, 7], [1, 3, 5, 11], [1, 3, 6, 10], [1, 3, 6, 11], [1, 3, 7, 10], [1, 4, 6, 9], [1, 4, 6, 10], [1, 4, 7, 9], [1, 4, 7, 10], [1, 5, 7, 9], [1, 5, 9, 11], [1, 6, 9, 11], [2, 4, 6, 9], [2, 4, 7, 8], [2, 4, 7, 9], [2, 5, 7, 8], [2, 5, 7, 9], [2, 5, 9, 11], [2, 6, 9, 11], [3, 5, 7, 8], [3, 7, 8, 10], [4, 7, 8, 10]]

示例:删除所有出现数字1的列表,然后

T=[[0, 2, 4, 6], [0, 2, 4, 8], [0, 2, 5, 8], [0, 2, 5, 11], [0, 2, 6, 11], [0, 3, 5, 8], [0, 3, 5, 11], [0, 3, 6, 10], [0, 3, 6, 11], [0, 3, 8, 10], [0, 4, 6, 10], [0, 4, 8, 10], delete([1, 3, 5, 7]), delete([1, 3, 5, 11]), delete([1, 3, 6, 10]), delete([1, 3, 6, 11]), delete([1, 3, 7, 10]), delete[1, 4, 6, 9], delete[1, 4, 6, 10], delete[1, 4, 7, 9], delete[1, 4, 7, 10], delete[1, 5, 7, 9], delete[1, 5, 9, 11], delete[1, 6, 9, 11], [2, 4, 6, 9], [2, 4, 7, 8], [2, 4, 7, 9], [2, 5, 7, 8], [2, 5, 7, 9], [2, 5, 9, 11], [2, 6, 9, 11], [3, 5, 7, 8], [3, 7, 8, 10], [4, 7, 8, 10]]

python中是否有算法或命令可以实现?

1 个答案:

答案 0 :(得分:4)

您可以使用列表压缩来做到这一点: [lst for lst in T if 1 not in lst]

或for循环:

final = []
for lst in T:
    if 1 not in lst:
        final.append(lst)

如果您正在学习Python,则列表理解是用于构建列表的单行for循环。

列表理解通常也比for循环快:

def for_loop(T):
    final = []    
    for lst in T:    
        if 1 not in lst:
            final.append(lst)
    return final

def list_comp(T):
    return [lst for lst in T if 1 not in lst]

%timeit for_loop(T)
3.02 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit list_comp(T)
2.16 µs ± 9.37 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)