Home > OS >  list of lists with particular columns made a typo and works
list of lists with particular columns made a typo and works

Time:08-19

I need to make a function that takes 2 lists as a parameter and returns a new list of lists created from the first list, and has the columns of the second list. if I have this:

'''

l_l = [[1,2,3,4,'a'],
        [5,6,7,8,'b'],
        [9,10,11,12,'c']
      ]
'''

needs to return this:

'''
print(fun(l_l, [1,3,4]))
print(fun2(l_l, [1,3,4]))
[[2, 4, 'a'], [6, 8, 'b'], [10, 12, 'c']]
'''

So I did this:

"""
def fun(l1, l2):
    new_l = []
    for i in l1:
        for j in l2:
            new_l.append(i[j])
    return new_l
"""

But this returns a simple list and not a list of lists.

Then I tried nested lists comprehension because I was sure it will return a list of lists. But I made a typo and worked great. When I corrected the typo, stoped working, says index out of range. This is with type and works:

"""
def fun2(l1, l2):
    new_l = [[l1[i] for i in l2] for l1 in l1]
    return new_l
"""

And this is without my first type mistake:

"""
def fun2(l1, l2):
    new_l = [[l1[i] for i in l2] for j in l1]
    return new_l
"""

Please, if someone can explain what's happening ? How it works with l1 in l1 ?

CodePudding user response:

This seems like a classic example of why one should use descriptive variable names. It is much harder to reason about l_l, new_l, l1 or l2 than it is to reason about original_list_of_lists, new_list_of_lists and new_sublist. The following code does what you expect:

original_list_of_lists = [[1, 2, 3, 4, "a"], [5, 6, 7, 8, "b"], [9, 10, 11, 12, "c"]]


def get_new_list_of_lists(orig_list: list[list], indexes_to_keep: list[int]):
    new_list_of_lists = []
    for sublist in orig_list:
        new_sublist = []
        for index_to_keep in indexes_to_keep:
            new_sublist.append(sublist[index_to_keep])
        new_list_of_lists.append(new_sublist)
    return new_list_of_lists


print(get_new_list_of_lists(original_list_of_lists, [1, 3, 4]))
# prints: [[2, 4, 'a'], [6, 8, 'b'], [10, 12, 'c']]

If you want this to be in a list comprehension, then this might be more clear:

original_list_of_lists = [[1, 2, 3, 4, "a"], [5, 6, 7, 8, "b"], [9, 10, 11, 12, "c"]]
indexes_to_keep = [1, 3, 4]

new_list_of_lists = [
    [sublist[index_to_keep] for index_to_keep in indexes_to_keep]
    for sublist in original_list_of_lists
]
  • Related