Python|从列表中查找重叠的元组
有时,在处理元组数据时,我们可能会遇到一个问题,即我们可能需要获取与某个元组重叠的元组。在使用几何时,这种问题可能会出现在数学领域。让我们讨论一些可以解决这个问题的方法。
方法#1:使用循环
在这种方法中,我们使用条件语句提取具有重叠的对,并将合适的匹配附加到列表保存记录中。
# Python3 code to demonstrate working of
# Find overlapping tuples from list
# using loop
# initialize list
test_list = [(4, 6), (3, 7), (7, 10), (5, 6)]
# initialize test tuple
test_tup = (1, 5)
# printing original list
print("The original list : " + str(test_list))
# Find overlapping tuples from list
# using loop
res = []
for tup in test_list:
if(tup[1]>= test_tup[0] and tup[0]<= test_tup[1]):
res.append(tup)
# printing result
print("The tuple elements that overlap the argument tuple is : "
+ str(res))
输出 :
The original list : [(4, 6), (3, 7), (7, 10), (5, 6)]
The tuple elements that overlap the argument tuple is : [(4, 6), (3, 7), (5, 6)]
方法#2:使用列表推导
也可以使用列表理解功能来完成此任务。这个方法和上面的方法类似,只是装在一个衬里,用作速记。
# Python3 code to demonstrate working of
# Find overlapping tuples from list
# Using list comprehension
# initialize list
test_list = [(4, 6), (3, 7), (7, 10), (5, 6)]
# initialize test tuple
test_tup = (1, 5)
# printing original list
print("The original list : " + str(test_list))
# Find overlapping tuples from list
# Using list comprehension
res = [(idx[0], idx[1]) for idx in test_list\
if idx[0] >= test_tup[0] and idx[0] <= test_tup[1]\
or idx[1] >= test_tup[0] and idx[1] <= test_tup[1]]
# printing result
print("The tuple elements that overlap the argument tuple is : "
+ str(res))
输出 :
The original list : [(4, 6), (3, 7), (7, 10), (5, 6)]
The tuple elements that overlap the argument tuple is : [(4, 6), (3, 7), (5, 6)]