Home > OS >  How to iterate over a list of lists of integers?
How to iterate over a list of lists of integers?

Time:10-08

As far as I know this question hasn't been asked.

If I have two lists like so:

a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]

How can I iterate over them while checking if the values of b_list fit the ascending order of the numbers in a_list? in this case b_list fits between [1, 2] and [5, 6] and should be appending in that spot. How would this be done in python?

When I use a for loop it tells me:

"TypeError: 'int' object is not subscriptable"

I used this code:

for sub_lst in a_lst:
    for lst in sub_lst:

CodePudding user response:

You can simply append b to a then sort all elements:

>>> a_list = [[1, 2], [5, 6], [7, 8]]
>>> b_list = [3, 4]
>>> sorted(a_list   [b_list])
[[1, 2], [3, 4], [5, 6], [7, 8]]

CodePudding user response:

you could use bisect_left to find the insertion index using a binary search (I'm assuming that there are no range overlaps in your data)

a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]

from bisect import bisect_left

i = bisect_left(a_list,b_list)
a_list.insert(i,b_list)

print(a_list)
[[1, 2], [3, 4], [5, 6], [7, 8]]

You can also do it by sequentially searching for the index of the first item that is greater than b_list.

a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]

i = next((i for i,a in enumerate(a_list) if b_list<a),len(a_list))
a_list.insert(i,b_list)

print(a_list)
[[1, 2], [3, 4], [5, 6], [7, 8]]

CodePudding user response:

If you want to stick with what you have (with the for loop) do

for index, sub_list in enumerate(a_list):
    if sub_list[0] < b_list[0]:
        continue
    elif sub_list[0] == b_list[0] and sub_list[1] < b_list[1]:
        continue
    else:
        a_list.insert(index, b_list)
        break

This will iterate through the list till you get to the right position (takes account of the second spot in case the first one is the same ie [3, 3] and b_list = [3,5]) and append b_list at the index where it stopped

  • Related