Search code examples
pythonlistcopying

Python: copying chosen rows form list to another


I'm trying to write a function that copies chosen rows from list to another, basing on third list that points which should be taken. "1" - copy row with this stuff, "0" omitt. Here is my code:

stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]

chooseThese = [1,0,1,1,0]

def fnChoose(arr1D, arr):
    new = []
    for digit in arr1D:
        for row in arr:
            if arr1D[digit] == 1:
                new.append(arr[row])
            else:
                continue
    return new


print (fnChoose(chooseThese, stuff))

As a result i wan't to get:

[[1, 2, 3], [100, 200, 300], [1000, 2000, 3000]]

Unfortunately my function doesn't work, idle dispalys following error:

Traceback (most recent call last):
  File "~\file.py", line 21, in <module>
    fnChoose(chooseThese, stuff)
  File "~\file.py", line 16, in fnChoose
    new.append(arr[row])
TypeError: list indices must be integers or slices, not list

What should i correct this function? How to append whole rows to list?


Solution

  • A more simple approach is to either use an indexed list instead of a 0/1 list, to create an indexed comprehension using enumerate or to use a combined list using zip:

    stuff = [
    [1, 2, 3],
    [10, 20, 30],
    [100, 200, 300],
    [1000, 2000, 3000],
    [10000, 20000, 30000],
    ]
    
    chooseThese = [1,0,1,1,0]
    
    # use enumerate (two variants)
    new = [s for index, s in enumerate(stuff) if chooseThese[index] == 1]
    print(new)
    new = [stuff[index] for index, choose in enumerate(chooseThese) if choose == 1]
    print(new)
    
    # use zip
    new = [s for choose, s in zip(chooseThese, stuff) if choose == 1]
    print(new)
    
    # use indexed chooser-variable
    chooseThese = [0,2,3]
    new = [stuff[index] for index in chooseThese]
    print(new)