3

I would like to compare between two list using item of the first list with index of the second list, and new list will append from second list for each matched.

a = [[1],[0],[0]]
b = [[1,2],[3,4],[5,6]]
c = []
for item in a:
     for i in range(len(b)):
          if item == b[i]:
              c.append(b[i])

the answer should like this:

c = [[3,4],[1,2],[1,2]]
6
  • the code is returning empty list Commented Jun 26, 2014 at 10:19
  • no, it does not work, it return [ ] Commented Jun 26, 2014 at 10:21
  • 1
    I can't understand where is the compare part according to your expected output, therefore i don't understand all the answers which only append an element from b by an index from list a Commented Jun 26, 2014 at 10:27
  • Can you change your a to be a list of ints, rather than a nested list? Commented Jun 26, 2014 at 10:29
  • actually, a is a result of index from comparing between another two different list. and from a, i need to produce another list from b which b index is match with the item in a Commented Jun 26, 2014 at 12:28

5 Answers 5

4

Simplest:

c = [b[i[0]] for i in a]

I recommend adding range checks though:

c = [b[i[0]] for i in a if (0 <= i[0] < len(b))]

EDIT: Based on your clarification of a, I recommend changing:

def findInstances(list1, list2):
    for i in list1:
        yield [pos for pos,j in enumerate(list2) if i==j] # This yields a list containing the value you want

to:

def findInstances(list1, list2):
    for i in list1:
        if (i in list2): 
            yield list2.index(i) # This yields only the value you want

This will flatten your list, and make the problem simpler. You can then use the following:

c = [b[i] for i in a if (0 <= i < len(b))]

Based on how you're getting a, the range checks are actually unnecessary. I left them in though, just in case you ever get a in a different way.

Sign up to request clarification or add additional context in comments.

Comments

2
In [1]: a = [[1],[0],[0]]

In [2]: b = [[1,2],[3,4],[5,6]]

In [3]: [b[x[0]] for x in a] 
Out[3]: [[3, 4], [1, 2], [1, 2]]

2 Comments

Why nested comprehensions? Just [b[x[0]] for x in a]
oh my!, thank you sooo much..i may look silly, but i'm totally new in programming especially in python, thank you again
2

using numpy indexing:

>>a = np.asarray(a)
>>b = np.asarray(b)
>>b[a]
array([[[3, 4]],

       [[1, 2]],

       [[1, 2]]])

Comments

1

Your algorithm is almost correct. The problem is with the if statement. If you tried print out item and b[i] before testing for equality you would see the problem.

>>> a = [[1],[0],[0]]
>>> b = [[1,2],[3,4],[5,6]]
>>> c = []
>>> for item in a:
>>>      for i in range(len(b)):
>>>           print("item == b[i] is {} == {} is {}".format(item, b[i], 
                      item == b[i]))
>>>           if item == b[i]:
>>>               c.append(b[i])
item == b[i] is [1] == [1, 2] is False
item == b[i] is [1] == [3, 4] is False
item == b[i] is [1] == [5, 6] is False
item == b[i] is [0] == [1, 2] is False
item == b[i] is [0] == [3, 4] is False
item == b[i] is [0] == [5, 6] is False
item == b[i] is [0] == [1, 2] is False
item == b[i] is [0] == [3, 4] is False
item == b[i] is [0] == [5, 6] is False

You have essentially been checking that each element in a and b for equality. Rather you want to check the elements in each item of a for equality with the index of b.

eg.

for item_a in a:
    for index_b, item_b in enumerate(b):
        # only check index 0 of item_a as all lists are of length one.
        print("item_a[0] == index_b is {} == {} is {}".format(item_a[0], 
                  index_b, item_a[0] == index_b))
        if item_a[0] == index_b:
            c.append(item_b)

produces:

item_a[0] == index_b is 1 == 0 is False
item_a[0] == index_b is 1 == 1 is True
item_a[0] == index_b is 1 == 2 is False
item_a[0] == index_b is 0 == 0 is True
item_a[0] == index_b is 0 == 1 is False
item_a[0] == index_b is 0 == 2 is False
item_a[0] == index_b is 0 == 0 is True
item_a[0] == index_b is 0 == 1 is False
item_a[0] == index_b is 0 == 2 is False

enumerate is a builtin helper function that returns a tuple containing the index and element for each element in a list (or anything that is iterable).

Unless you need to I would also recommend flattening a as having nested lists is redundant here ie. a = [1, 0, 0].

Having said all this, if you can get your head around list comprehensions then coding a solution would be much simpler -- as evidenced by the other answers to your question.

2 Comments

No problem, you said you were just starting out and so I figured you were really looking for why your code wasn't working rather than an actual answer.
When in doubt, print it out!
0

this is how i comparing between another two different list.

def findInstances(list1, list2):
    for i in list1:
    yield [pos for pos,j in enumerate(list2) if i==j]


list1 = [0.1408, 0.1456, 0.2118, 0.2521, 0.1408, 0.2118]
list2 = [0.1408, 0.1456, 0.2118, 0.2521, 0.1254, 0.1243]
list3 = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
res = list(findInstances(list1, list2))

and res produce the output as 'a' in the first question

thank you

1 Comment

I updated my answer, with a suggestion for the findInstances function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.