如何从 python 范围内排除列表?

How to exclude list from range in python?

所以我根据适合特定条件的设定范围内的值创建了一个列表,现在稍后我想检查同一范围内的所有值,但不包括放入该列表的值..这可能吗?如果没有,还有其他选择吗?

filled_columns = []
for b in range(0,7):
    if board[0,b] == 1 or board[0,b] == 2:
        filled_columns.append(b)
for b in range(0,7) #but excluding values from "filled_columns" list

如果我对你的问题的理解正确,你可以使用列表理解将项目复制到一个新列表中,过滤掉你不想要的。例如:

list1 = range(20)
filterlist = [4,6,8,9,14]

filtered=[item for item in list1 if item not in filterlist]
print filtered

因此,对于您的示例,将最后一行替换为:

checklist = [b for b in range(0,7) if b not in filled_columns]
for b in checklist:
    # do stuff with b

有可能,你可以只检查另一个for循环中的值b是否存在于filled_list中,如果不存在,则执行你的逻辑,如果存在,什么都不做。

例子-

filled_columns = []
for b in range(0,7):
    if board[0,b] == 1 or board[0,b] == 2:
        filled_columns.append(b)
for b in range(0,7):
    if b not in filled_columns:
        #do your logic

或者为了获得更好的性能,您可以将 filled_columns 创建为 set ,其搜索操作是常数时间。

例子-

filled_columns = set()
for b in range(0,7):
    if board[0,b] == 1 or board[0,b] == 2:
        filled_columns.add(b)
for b in range(0,7):
    if b not in filled_columns:
        #do your logic

您不只是要一份未填写的列的列表吗?除非我误解了你的问题,否则这可以在没有额外列表的情况下一次性完成,更不用说设置

emptycols = [b for b in range(7) if board[0,b] != 1 and board[0,b] !=2]

你也可以使用集合。

a  = list(set(range(7)) - set(filled_columns))