简体   繁体   中英

remove all elements within sublists that are at a specific index - python 2

I have a nested list, and I'd like to remove the 2nd element for all the sublists throughtout the list.

The list is as fallows,

A=[[[a, b], [c, d], [g, h]]
   [[e, f], [g, h], [t, f]]]

Id like to remove the i[1] elements from each sublist within A to get this result,

A=[[[a, b],[g, h]]
   [[e, f], [t, f]]]

Ive tried doing A.remove(A[i][1]) but it ends in a "list indices must be integers, not list' error. Any input on how to do this would be a help.

A simple for loop can solve your problem:

A=[[['a', 'b'], ['c', 'd'], ['g', 'h']],
   [['e', 'f'], ['g', 'h'], ['t', 'f']]]

for l in A:
    l.pop(1)

# A == [[['a', 'b'], ['g', 'h']],
#       [['e', 'f'], ['t', 'f']]]

You can use a list comprehension which is the 'pythonic' way of doing these things:

A=[[['a', 'b'], ['c', 'd'], ['g', 'h']],
   [['e', 'f'], ['g', 'h'], ['t', 'f']]]

[inner.pop(1) for inner in A]

This is equivalent to for loop. Pop removes an element at the index and Python starts with index 0 so index 1 is the second element.

I think mutating the list is not the best option in general. Most python code you'll find will prefer to return a modified list instead. For example:

A = [[l[0], *l[2:]] for l in A]

The advantage here is that you don't risk any side effect:

A = [
    [['a', 'b'], ['c', 'd'], ['g', 'h']],
    [['e', 'f'], ['g', 'h'], ['t', 'f']],
]

B = A
A = [[l[0], *l[2:]] for l in A]

print(B)

Would still output the original list:

[[['a', 'b'], ['c', 'd'], ['g', 'h']], [['e', 'f'], ['g', 'h'], ['t', 'f']]]

Whereas if you mutate A :

for l in A:
    l.pop(1)

print(B)

This would output:

[[['a', 'b'], ['g', 'h']], [['e', 'f'], ['t', 'f']]]

This is not always true, but unless you have a good reason to, don't use mutations.

I don't believe in using for loops for list manipulation. You can use map and lambda to apply a transformation to all list items. To keep only the first and third columns you can do:

[*map(lambda x: (x[0], x[2]), A)]

or

list(map(lambda a, b, c: (a, c), *zip(*A)))

They both yield:

[(['a', 'b'], ['g', 'h']), (['e', 'f'], ['t', 'f'])]

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