我有两个具有相同元素数量的列表,但时间戳是波动的,并且与其他列表的相同元素不匹配。有没有一种组织列表的方法,以使元素与另一个列表中的相同索引相对应?现在我有
sorted1 = []
sorted2 = []
for i in list1:
for x in list2:
if (i-1 <= x <= i+1):
sorted1.append(i)
sorted2.append(x)
break
这可行,但是运行非常慢。
我的清单是需要配对的时代。
[1412121504, 1412121512, 1412121516, 1412121520, 1412121525, 1412121580]
[1412121470, 1412121515, 1412121525, 1412121560, 1412121580, 1412121600]
如果它们在另一列表中的对应时间都在1秒之内,那么我不想将它们包括在内。我希望它看起来像这样,
[1412121516, 1412121525]
[1412121515, 1412121525]
感谢您阅读所有这些内容。
您可以在对列表进行排序之后维护两个计数器,然后在比较元素时将它们一起移动:
list1 = [1412121504, 1412121512, 1412121516, 1412121520, 1412121525, 1412121580]
list2 = [1412121470, 1412121515, 1412121525, 1412121560, 1412121580, 1412121600]
# sort the lists
list1.sort()
list2.sort()
# maintain two counters to each of the lists
list1i = 0
list2i = 0
paired1 = []
paired2 = []
while list1i < len(list1) and list2i < len(list2):
cur1 = list1[list1i]
cur2 = list2[list2i]
# too small, advance the first list counter
if cur1 < cur2 - 1:
list1i += 1
# too large, advance the second list counter
elif cur1 > cur2 + 1:
list2i += 1
# we found a pair, increment both to avoid duplicates
else:
paired1.append(cur1)
paired2.append(cur2)
list1i += 1
list2i += 1
print(paired1, paired2)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句