gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:11:05 24 4
gpt4 key购买 nike

我在 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中有算法或者命令可以做到吗??

最佳答案

你可以用列表理解来做到这一点:[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)

关于python - 在 python 2 中删除具有条件的列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56189151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com