【问题标题】:Python: How to check if value is in between multiple indices of two lists?Python:如何检查值是否在两个列表的多个索引之间?
【发布时间】:2021-03-03 16:30:43
【问题描述】:

我正在使用 cv2 逐帧分析视频,如果帧号在某些时间戳之间,我想将帧保存为 1,否则保存为 0。 我有两个列表,一个是开始时间,一个是结束时间:

start_times = [0, 10, 15]
end_times = [2, 12, 17]

我想将帧号 0,1,2 和 10,11,12 和 15,16,17 的帧保存为 1,其他帧保存为 0。

我的代码将正确的帧保存为 1,但将不需要的帧保存为 0,因为我使用的是 for 循环。请参阅下面的简化示例:

start_times = [0,10,15]
end_times = [2,12,17]

currentframe = 0

while True: 
    try:
        for index,time in enumerate(start_times):
            if start_times[index] <= currentframe <= end_times[index]:
                print('save images as 1')
            else:
                print('save images as 0')
        currentframe += 1

        if currentframe == 20:
            break

    except IndexError:
        break

第一帧的输出:

save images as 1
save images as 0
save images as 0

如何更改我的代码以使第一帧仅保存为 1?

【问题讨论】:

  • 你想知道你总共得到了多少个 1 吗?
  • @VIVID 不,如果当前帧位于两个列表的相同索引的值之间(因此在本例中介于 0&2、10&12、15&17 之间),我想保存当前帧。我没有添加保存部分以使示例更清晰。

标签: python for-loop list-comparison


【解决方案1】:

我不确定我是否清楚地理解了你,但试试这个并告诉我它是否是你想要的:

start_times = [0,10,15]
end_times = [2,12,17]

times = sorted(start_times + end_times)
print(times)

i = 0
while i + 1 < len(times):
  k = times[i]
  while k <= times[i + 1]:
    if i % 2 == 0:
      print('save [frame {}] as 1'.format(k))
    else:
      print('save [frame {}] as 0'.format(k))    
    k += 1
  i += 1

【讨论】:

  • @DanielvandenCorput 很高兴它有帮助!
【解决方案2】:

我的一个朋友通过使用范围给了我解决方案:

current_frame = 0
start_times = [0, 10, 15]
end_times = [2, 12, 17]
ranges = [range(start, stop) for start, stop in zip(start_times, end_times)]

while True:
    if any([current_frame in my_range for my_range in ranges]):
        print('save image as 1')
    else:
        print('save image as 0')
...

【讨论】:

    【解决方案3】:

    我想这就是你要找的东西?

    while curr_frame < 20:
        is_in = any(filter(lambda start_end: start_end[0] <= curr_frame <= start_end[1],
                           zip(start_times, end_times))))
        print(f'Save image as {int(is_in)}')
        curr_frame += is_in
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多