简体   繁体   中英

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]:
        Region_frontier.append(i)
print Region_frontier

but i got this error message.

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

please kindly help me. thank you in advance ^^

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]:
        Region_frontier.append(cur)

First of all I assume that by previous you mean the current element which you are iterating. Also, I want to mention that you have a list of lists, not a set of tuple. Since python has keywords like that so you should take care while using those words. Now talking about your problem

The problem is you are iterating over 'int' not a list. When you do i in sorted_Region 'i' is an element of that list not its iterator. So you can do the following

Region_frontier = []
i = 0
while i < len(sorted_Region)-1:
    if sorted_Region[i+1][1] >= sorted_Region[i][1] and sorted_Region[i+1][2] < sorted_Region[i][2]:
        Region_frontier.append(sorted_Region[i])
print(Region_frontier)

For i+1[1] , getting the indexed item of 'int' object is ill-grammar. For the intended purpose, no index in the for loop for sorted_Region , so it is not possible to get the " previous tuple ".

To iterate the sorted_Region and compare to the nearby item, try use tuple index(real index i that ranges from 0 to len(sorted_Region) - 1 ):

Region_frontier = []
for i in range(0, len(sorted_Region) - 1):
    if sorted_Region[i+1][1] >= sorted_Region[i][1] and sorted_Region[i+1][2] < sorted_Region[i][2]:
        Region_frontier.append(i)
print Region_frontier
for index in range(len(sorted_Region)-1):
    if sorted_Region[index+1][i] >= sorted_Region[index][1] and sorted_Region[index+1][2]<sorted_Region[index][2]:
        Region_frontier.append(i)
print Region_frontier

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM