Outcast
Outcast

Reputation: 5117

Remove some same-index elements from two lists based on one of them

Let's suppose that I have these two lists:

a = [{'id': 3}, {'id': 7}, None, {'id': 1}, {'id': 6}, None]
b = ['5', '5', '3', '5', '3', '5']

I want to filter both at the same-index based though only on a and specifically on filtering out the None elements of a.

So finally I want to have this:

[{'id': 3}, {'id': 7}, {'id': 1}, {'id': 6}]
['5', '5', '5', '3']

I have written this code for this:

a_temp = []
b_temp = []

for index, el in enumerate(a):

    if el:
        a_temp.append(a[index])
        b_temp.append(b[index])

a = a_temp[:]
b = b_temp[:]

I am wondering though if there is any more pythonic way to do this?

Upvotes: 0

Views: 36

Answers (2)

Green Cloak Guy
Green Cloak Guy

Reputation: 24711

This solution

  1. uses zip() to group corresponding elements of a and b together
  2. Makes a list of 2-tuples of corresponding elements, such that the corresponding element of a is not None
  3. Use the zip(*iterable) idiom to flip the dimensions of the list, thus separating the single list of 2-tuples into two lists of singletons, which we assign to new_a and new_b
a = [{'id': 3}, {'id': 7}, None, {'id': 1}, {'id': 6}, None]
b = ['5', '5', '3', '5', '3', '5']

new_a, new_b = zip(*((x, y) for x, y in zip(a, b) if x))
# new_a = ({'id': 3}, {'id': 7}, {'id': 1}, {'id': 6})
# new_b = ('5', '5', '5', '3')

Upvotes: 2

SimfikDuke
SimfikDuke

Reputation: 1148

If you just want a simple solution, please try:

a = [{'id': 3}, {'id': 7}, None, {'id': 1}, {'id': 6}, None]
b = ['5', '5', '3', '5', '3', '5']
n = []
for i in range(len(b)):
    if a[i] is None:
        n.append(i)

for i in sorted(n, reverse=True):
    a.pop(i)
    b.pop(i)

a
[{'id': 3}, {'id': 7}, {'id': 1}, {'id': 6}]
b
['5', '5', '5', '3']

Upvotes: 1

Related Questions