Dini KF Dini KF - 1 year ago 64
Python Question

Making new list of list with some condition of other list

I am new to python and still struggle with it.
So can you guys help me with this?

I have this list of lists:

sorted_Region: [[J, 0.80, 0.30], [H, 0.80, 0.21], [I, 0.87, 0.19], [G, 0.88, 0.15], [D, 0.96, 0.14], [B, 0.97, 0.14], [A, 1.01, 0.11], [C, 1.05, 0.15], [F, 1.06, 0.04], [E, 1.55, 0.22]]

And I want to make new list of lists with condition:
if the next list has second element value greater or equal to the second element of current list AND the next list has third element value less than the third element of current list.

I tried this code

Region_frontier = []
for i in sorted_Region:
if i+1[1] >= i[1] and i+1[2] < i[2]:
print Region_frontier

but i got this error message.

TypeError: 'int' object has no attribute '__getitem__'

please kindly help me. thank you in advance ^^

Answer Source

You're trying to use index operator on integer which causes the error: i+1[1]. Instead of using indexing you could iterate over the pairs on the list with zip and islice:

from itertools import islice

Region_frontier = []
for prev, cur in zip(sorted_Region, islice(sorted_Region, 1, None)):
    if cur[1] >= prev[1] and cur[2] < prev[2]:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download