简体   繁体   中英

IndexError: list index out of range - having

I have the following list called row:

[[[463, 100, 77, 9]], [[41, 418, 121, 175], [168, 419, 170, 176], [344, 421, 106, 175], [456, 422, 59, 175], [521, 423, 80, 174], [607, 424, 221, 176], [834, 427, 108, 174], [948, 428, 141, 174]], [[40, 601, 1046, 74]], [[40, 675, 119, 41], [167, 676, 80, 41], [255, 677, 80, 40], [343, 678, 104, 40], [520, 679, 78, 40], [455, 679, 57, 40], [606, 680, 219, 42], [833, 682, 106, 41], [947, 683, 138, 41], [851, 684, 37, 7]], [[39, 724, 120, 41], [166, 725, 81, 41], [342, 726, 105, 41], [254, 726, 81, 41], [454, 727, 58, 41], [519, 728, 79, 40], [605, 729, 219, 41], [833, 731, 105, 40], [966, 732, 119, 41], [946, 732, 16, 39], [850, 733, 38, 7]] ...]

Now I wanted to extract always the first and the second value. As you can see some elements of the list have only one sublist (like the first element), while others have 8 or more elements. When I try to iterate through it with the following code:

list_xy = []
for r in range(len(row)):
    for i in range(len(row[i])):
        list_xy.append((row[i][j][0], row[i][j][1]))

this error pops up:

Traceback (most recent call last):
  File "/Users/Desktop/tempCodeRunnerFile.py", line 190, in <module>
    list_xy.append((row[i][j][0], row[i][j][1]))
IndexError: list index out of range

My assumption is that it pops up, because I do have only one element in the first sublist (which is [463,100,77,9]), but I do not know how to get it running. I appreciate all helpful suggestions.

looks like you want to extract the first 2 elements from each very inner list but your wrong assumption is that you have the same amount of lists at the first and second level of nastiness, to fix you can use:

list_xy = []
for r in row:
    for l in r:
        list_xy.extend(l[:2])

or even better you can use a list comprehension:

[e for r in row for l in r for e in l[:2]]

output:

[463, 100, 41, 418, 168, 419, 344, 421, 456, 422, 521, 423, 607, 424, 834, 427, 948, 428, 40, 601, 40, 675, 167, 676, 255, 677, 343, 678, 520, 679, 455, 679, 606, 680, 833, 682, 947, 683, 851, 684, 39, 724, 166, 725, 342, 726, 254, 726, 454, 727, 519, 728, 605, 729, 833, 731, 966, 732, 946, 732, 850, 733]
list_xy = [(i[0][0], i[0][1]) for i in row]

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