[英]Merge two list of tuples based on overlapp python
給定兩個列表 x, y 使得它們都已初始化如下:
x = [(0, 3), (5, 8), (16, 19), (21, 24), (28, 30), (40, 42), (46, 47), (50, 54), (58, 63), (69, 71)]
y = [(9, 10), (26, 27), (29, 31), (35, 36), (41, 43), (48, 49), (66, 67), (70, 72), (77, 78), (85, 86)]
我想形成一個新的元組列表,其中每個元組都有來自 x 的連續元組和來自 y 的重疊元組。
對於上面的示例,輸出將是:
[((5, 8) (9, 10) (16, 19)), ((21, 24) (26, 27) (28, 30)), ((28, 30) (29, 31) (40, 42)), ((28, 30) (35, 36) (40, 42)), ((40, 42) (41, 43) (46, 47)), ((46, 47) (48, 49) (50, 54)),((58, 63) (66, 67) (69, 71))]
我的代碼:
lst = []
for i in range(len(x)):
if i+1 < len(x):
context = x[i],x[i+1]
for j in y:
if j[0] >= context[0][0] and j[0] <= context[1][0]:
lst.append((context[0],j,context[1]))
我需要更好更有效的方法來編寫這段代碼。
您可以使用兩個變量來跟蹤 x 和 y 列表中的索引。 使用問題中指定的條件,只要滿足給定的條件,就可以增加這些指數。 在每次迭代中,該算法檢查是否x[i][0] < y[j][0]
和x[i+1][1] > y[j][1]
(由x
連續元組。如果這個條件為真,我們增加j
(y-index) 以便我們可以檢查下一個元素是否在給定的范圍內。否則,我們增加i
(x-index) 並重復該過程。
x = [(0, 3), (5, 8), (16, 19), (21, 24), (28, 30), (40, 42), (46, 47), (50, 54), (58, 63), (69, 71)]
y = [(9, 10), (26, 27), (29, 31), (35, 36), (41, 43), (48, 49), (66, 67), (70, 72), (77, 78), (85, 86)]
i = 0
j = 0
result = list()
while i < len(x) - 1 and j < len(y):
if y[j][0] > x[i][0] and y[j][1] < x[i + 1][1]:
result.append((x[i], y[j], x[i + 1]))
j += 1
else:
i += 1
print(result)
輸出 -
[((5, 8), (9, 10), (16, 19)),
((21, 24), (26, 27), (28, 30)),
((28, 30), (29, 31), (40, 42)),
((28, 30), (35, 36), (40, 42)),
((40, 42), (41, 43), (46, 47)),
((46, 47), (48, 49), (50, 54)),
((58, 63), (66, 67), (69, 71))]
您可以使用Python 排序
from operator import itemgetter, attrgetter
output = sorted((x + y), key=itemgetter(0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.