我有一个包含20000个列表的列表。我将每个列表的第3个元素用作标志。只要至少一个元素的标志为0,我想在此列表上执行一些操作,就像:my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....]开始时,所有标志均为0。我使用while循环检查至少一个元素的标志是否为0:def check(list_): for item in list_: if item[2] == 0: return True return False如果check(my_list)返回True,那么我将继续处理我的列表:while check(my_list): for item in my_list: if condition: item[2] = 1 else: do_sth()实际上,我想在对my_list进行迭代时删除该元素,但是由于对其进行迭代,所以不允许删除项目。原始的my_list没有标志:my_list = [["a", "b"], ["c", "d"], ["e", "f"], .....]由于在迭代过程中无法删除元素,因此发明了这些标志。但是my_list包含许多项,并且while循环在每个for循环中读取所有这些项,这会花费大量时间!你有什么建议吗?
3 回答

牧羊人nacy
TA贡献1862条经验 获得超7个赞
您可以像这样使用itertools的takewhile,一旦满足条件会使您的语句失败,它将停止。相反的方法是dropwhile
for x in itertools.takewhile(lambda x: x[2] == 0, list)
print x

噜噜哒
TA贡献1784条经验 获得超7个赞
如果要检查列表中的任何项目是否违反条件,请使用all:
if all([x[2] == 0 for x in lista]):
# Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)
要删除所有不匹配的元素,请使用 filter
# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)
添加回答
举报
0/150
提交
取消