简体   繁体   English

如何查找列表中的数字是否在列表中的两个数字的区间中?

[英]How to find if a number in a list is in a interval of two numbers in a list?

I have two sorted lists of same length, eg: 我有两个相同长度的排序列表,例如:

first_list = [3, 5, 15, 19, 23]
second_list = [0, 11, 22, 34, 43]

I wish to know if the numbers of the first list are in the interval formed by the two numbers in a row from the second list. 我想知道第一个列表的编号是否在第二个列表的一行中由两个数字组成的区间中。 Then, i wish to print the value of the first list and the interval. 然后,我希望打印第一个列表的值和间隔。

As an example: 举个例子:

3 in range(0,11) # True
5 in range(0,11) # True
15 in range(0,11) # False, next
15 in range(11,22) # True

and so on. 等等。

first_list = [3, 5, 15, 19, 23]
second_list = [0, 11, 22, 34, 43]

aux = 0
count = 1
n_iterations = len(first_list)
iteration = 0
while iteration != n_iterations:
    iteration += 1
    for i in first_list: 
        counter = first_list.index(i)
        try:        
            interval = range(second_list[aux],second_list[count])        
            if i in interval:
                print(i, 'in', interval)
            if i not in interval:    
                aux += 1
                count += 1    
                interval = range(second_list[aux], second_list[count])            
                if i in interval:
                    print(i, 'in' ,interval)
        except IndexError:
            break

The code i've tried does actually work. 我试过的代码确实有效。 But it seems so inefficient and 'hard-to-read' that there must be another way to do it. 但它似乎效率低下且“难以阅读”,必须采用另一种方式来实现。

edit: Since the question was updated, I updated my answer a little. 编辑:由于问题已更新,我稍微更新了我的答案。 I happily concede that this solution is not optimal, and takes more time than user7440787's solution. 我很高兴地承认这个解决方案不是最优的,并且比用户7440787的解决方案花费更多的时间。 I focused more on the "hard-to-read" than "inefficient" part of the problem. 我更关注问题的“难以阅读”而非“低效”部分。


First, my answer, then some explanations. 首先,我的答案,然后一些解释。

first_list = [3, 5, 15, 19, 23]
second_list = [0, 11, 22, 34, 43]

for low,high in zip(second_list, second_list[1:]):
    for val in first_list:
        if low <= val <= high:
            print("{} is in {}".format(val, (low, high)))

Output: 输出:

3 is in (0, 11)
5 is in (0, 11)
15 is in (11, 22)
19 is in (11, 22)
23 is in (22, 34)

This gives you simple elegance, while still being readable. 这为您提供简单优雅,同时仍然可读。 It's always a fun challenge to stick everything on to one line, but the code is much easier to handle when you break it into significant parts. 将所有内容都放在一行上总是一个有趣的挑战,但是当您将代码分解为重要部分时,代码更容易处理。 Of course, there are other ways you could have done this, but this shows off quite a few niceties of python. 当然,还有其他方法可以做到这一点,但这显示了很多python的细节。

zip(second_list, second_list[1:]) goes through the list of pairs in second_list. zip(second_list, second_list[1:])遍历second_list中的对列表。 The [1:] slices the list to be all but the first element of it, while the zip takes the two views of the list and yields a tuple for each pair, which then get assigned to low and high. [1:]将列表分割为除了它的第一个元素以外的所有元素,而zip获取列表的两个视图并为每对产生一个元组,然后将其分配给低和高。

low <= val <= high is a logical error in C, C++ or C#, but is perfectly right in python. low <= val <= high是C,C ++或C#中的逻辑错误,但在python中完全正确。 It is defined as "low <= val and val <= high", which is exactly what you're looking for in this case. 它被定义为“low <= val和val <= high”,这正是你在这种情况下所寻找的。

Using str.format is an easy way to output all types of variables in python. 使用str.format是在python中输出所有类型变量的简单方法。

If you want to print the first time an entry is not in the list, then you need: 如果要在第一次打印条目不在列表中时,则需要:

first_list = [3, 5, 15, 19, 23]
second_list = [0, 11, 22, 34, 43]
regions = list(zip(second_list[:-1],second_list[1:]))
n, i = 0, 0
print_stm = '%i %s in range(%i,%i)'
while n < len(regions) and i < len(first_list):
    if regions[n][0] <= first_list[i] <= regions[n][1]:
        print(print_stm % ((first_list[i], '') + regions[n]))
        i+=1
    else:
        print(print_stm % ((first_list[i], 'not') + regions[n]))
        n+=1

The result is: 结果是:

3 in range(0,11)
5 in range(0,11)
15 not in range(0,11)
15 in range(11,22)
19 in range(11,22)
23 not in range(11,22)
23 in range(22,34)

If you're only interested in knowing the intervals for each entry in first_list , you can simplify it to this: 如果您只想知道first_list每个条目的间隔,可以将其简化为:

first_list = [3, 5, 15, 19, 23]
second_list = [0, 11, 22, 34, 43]
regions = zip(second_list[:-1],second_list[1:])
intervals = [ (i, n) for i in first_list for n in regions if n[0] < i < n[1]]

The result is: 结果是:

[(3, (0, 11)), (5, (0, 11)), (15, (11, 22)), (19, (11, 22)), (23, (22, 34))]

One line solution for all possible pairs of ranges defined by the second list. 针对由第二个列表定义的所有可能的范围对的一行解决方案。

Your code seems fine but here is a shorter version: 你的代码似乎很好,但这是一个较短的版本:

# define all duo pairs based on `second_list`
all_pairs = [[second_list[p1], second_list[p2]] for p1 in range(len(second_list)) for p2 in range(p1+1,len(second_list))]

results = list()
results.append([[element,"is in", (all_pairs[i][0],all_pairs[i][1])] for element in first_list for i in range(len(all_pairs)) if element in range(all_pairs[i][0],all_pairs[i][1])])

If I understood correctly, the above should work. 如果我理解正确,上述应该有效。

Output: 输出:

[[[3, 'is in', (0, 11)],
  [3, 'is in', (0, 22)],
  [3, 'is in', (0, 34)],
  [3, 'is in', (0, 43)],
  [5, 'is in', (0, 11)],
  [5, 'is in', (0, 22)],
  [5, 'is in', (0, 34)],
  [5, 'is in', (0, 43)],
  [15, 'is in', (0, 22)],
  [15, 'is in', (0, 34)],
  [15, 'is in', (0, 43)],
  [15, 'is in', (11, 22)],
  [15, 'is in', (11, 34)],
  [15, 'is in', (11, 43)],
  [19, 'is in', (0, 22)],
  [19, 'is in', (0, 34)],
  [19, 'is in', (0, 43)],
  [19, 'is in', (11, 22)],
  [19, 'is in', (11, 34)],
  [19, 'is in', (11, 43)],
  [23, 'is in', (0, 34)],
  [23, 'is in', (0, 43)],
  [23, 'is in', (11, 34)],
  [23, 'is in', (11, 43)],
  [23, 'is in', (22, 34)],
  [23, 'is in', (22, 43)]]]

Here's what i've done : 这就是我所做的:

first_list = [3, 5, 15, 19, 23]
second_list = [0, 11, 22, 34, 43]

L = list(zip(second_list[:-1], second_list[1:]))
i = 0
n = 0
interval = L[i]

while  n < len(first_list):
    nb = first_list[n]
    while nb not in range(interval[0],interval[1]):
        print(nb, ' is not in range', interval)
        i += 1
        if i >= len(L):
            break
        interval = L[i]
    if i >= len(L):
        break
    print(nb, ' is in range', interval)
    n += 1

The output : 输出 :

3  is in  range(0, 11)
5  is in  range(0, 11)
15  is not in  range(0, 11)
15  is in  range(11, 22)
19  is in  range(11, 22)
23  is not in  range(11, 22)
23  is in  range(22, 34)

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

相关问题 有关数字列表和间隔列表,请查找每个数字所在的时间间隔 - For a list of numbers and a list of intervals, find the interval in which each number is located 如何查找列表中的数字是否是其他两个数字的乘积? - How to find if a number in the list being the product of other two numbers? 如何在数字列表中找到最多数量的因子? - How to find the most number of factors in a list of numbers? 找到两个排序列表中是否存在数字的更好方法 - Better way to find if a number is present in between two numbers of a sorted list 从列表中找出两个相加为特定数字的数字 - Find two numbers from a list that add up to a specific number 在数字列表中找到最大的数字 - Find the greatest number in a list of numbers 如何生成具有固定数量元素、固定起始值和结束值但可变间隔长度的数字列表? - How to generate a list of numbers with a fixed number of elements, fixed start and end values but variable interval lengths? 如何在列表中找到与给定数字不相邻的数字之和? - How can I find the sum of numbers in a list that are not adjacent to a given number? 如何在带有绑定数字的列表中找到最大数字 - How to find the max number(s) in a list with tied numbers 如何在列表中找到一对数字,使总和为给定数字 - How to find pair of numbers in a list which makes a sum as given number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM