multiple iteration of the same list

104 views Asked by At

I have one list of data as follows:

from shapely.geometry import box

data = [box(1,2,3,4), box(4,5,6,7), box(1,2,3,4)]
sublists = [A,B,C]

The list 'data' has following sub-lists:

A = box(1,2,3,4)
B = box(4,5,6,7)
C = box(1,2,3,4)

I have to check if sub-lists intersect. If intersect they should put in one tuple; and if not intersect should put in different tuple. The expected result is:

result = [(A,C), (B)]

How to do it?

I tried it as:

results = []
for p,c in zip(data,sub_lists):
    for x in data:
        if p.intersects(x): ##.intersects return true if they overlap else false
            results.append(c)
print results
1

There are 1 answers

0
hpaulj On BEST ANSWER

Without downloading shapely, I think what you want to do with lists can be replicated with strings (or integers):

In [221]: data=['one','two','three']    
In [222]: data1=['one','four','two']

In [223]: results=[[],[]]
In [224]: for i in data1:
    if i in data:
        results[0].append(i)
    else:
        results[1].append(i)
   .....:         

In [225]: results
Out[225]: [['one', 'two'], ['four']]

Replace the i in data with your intersects tests. The first sublist of results contains the elements of data1 for which the test is true. The second sublist contains the elements where it is false.

Your question is a little confusing in that data and sublists appear to contain the same elements. So maybe you aren't testing whether A is in data (or intersect with an element of data), but whether A intersects with an other element of [A,B,C], etc.

In any case, the key to collecting the results is to have two (or more) slots in results, where you can put i depending on the test. results could also be a dictionary, or could be two different variables. e.g. results={'found':[],'lost':[]}.

Do we need to work more on the test?

A 'intersects with' any of [B,C]
B 'intersects with' any of [A,C]
C 'intersects with' any of [A,B]