Search code examples
pythonarrayspython-3.xfor-looptry-except

Python 3.x: Print specific array items


I have two nested arrays which can look like this:

firstArray=[[1,10],[11,31],[32,40],[41,61],[62,78]]
secondArray=[[1,10],[12,32],[33,39],[41,78]]

I now want to search the elements of secondArray in firstArray. I want two events to be distinguished:

1: if the element is found directly, I want to print it.

2: If it is not found, I want to print the preceeding and following element, or the elements it spans/the elements that contain it.

For example, for second Array's [1,10] I want to print firstArray's[1,10], but for secondArray's [12,32] I want to print firstArrays's [11,31] and [32,40]. For secondArray's [33,39] I want to print firstArray's [32,40] and so on.

I know, that I can access the two arrays with a nested for loop and that I can access the elements via indexing. I am having trouble to do the part, if there are no direct hits.

for the direct hits, I am doing the following:

foundYou=[]
for entry in firstArray:
    for element in secondArray:
        if(entry[0] == element[0]) and (entry[1] == element[1]):
            foundYou.append(element)

I also did some research about indexing, but could not figure out, how to solve this. I also thought of using <=, >=, < and >, but it would then print all elements with a smaller number than the search at first position, but it would ofc print a lot more than I want.

I could "index" using a map and another array with values from 1...length of array, but that seems to be a rather complicated way to achieve what I want.

Thanks in advance :)


Solution

  • You can try this, I am printing the value and it's corresponding result.

    firstArray=[[1,10],[11,31],[32,40],[41,61],[62,78]]
    secondArray=[[1,10],[12,32],[33,39],[41,78]]
    
    foundYou=[]
    for second in secondArray:
        for firstindex,first in enumerate(firstArray):
            if second == first:
                foundYou.append(first)
                print(second,":",first)
            else:
                if second[0] >= first[0] and second[1] <= first[1]:
                    foundYou.append(first)
                    print(second,":",first)
                else:
                    try:
                        if second[0] >= first[0] and second[1] <= firstArray[firstindex+1][1] and second[0] < first[1]:
                            foundYou.append(first)
                            foundYou.append(firstArray[firstindex+1])
                            print(second,":",first,firstArray[firstindex+1])
                    except IndexError:
                        pass
    

    Output:

    [1, 10] : [1, 10]
    [12, 32] : [11, 31] [32, 40]
    [33, 39] : [32, 40]
    [41, 78] : [41, 61] [62, 78]