繁体   English   中英

查找列表中乱序元素的有效方法

[英]Efficient way to find elements in list out of order

鉴于此列表

[True, False, True, True, False, True, False, False]

我想找到该列表中所有在True元素之间混合为False的元素。 意义:

[True, True, True, True, True, False, False, False]

不会产生任何结果,上面的列表应该产生:

[1, 4]

我目前正在编写一个循环,试图记住 state 向后走该列表,但我认为可能有更有效的方法。 索引本身并不是真正需要的,因为我实际上是在添加列表中唯一的元素

尝试这个,

# zip both the array to create a tuple & yield those.
for index, (n, m) in enumerate(zip([True, False, True, False],
                                   [True, True, True, True])):
    if n != m:
        print(index)

Output

(1,3)

枚举zip

也许你可以这样做

test = [True, False, True, True, False, True, False, False]

start = None
found = None
end = None

for i in range(len(test)):
    if test[i] is False:
        if start is None:
            start = i
        else:
            found = i
    elif found is not None:
        end = found

if start is not None and end is not None:
    print(start)
    print(end)
# Create the list li = [True, False, True, True, False, True, False, False] # iterate from front until the first True value and remove all the False values for i in li: if not i: li.pop() if i: break # Out: [True, False, True, True, False, True, False, False] # Iterate from back until the first True value and remove all the False values for i in reversed(li): print(i) if i: break if not i: li.pop() # Out: [True, False, True, True, False, True] # Find the indices of remaining False values [i for i,x in enumerate(li) if not x] # Out: [1, 4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM