Reputation: 1
My problem is this. These are the two lists
codes = ['a', 'b', 'c', 'a', 'e', 'f', 'g', 'a', 'i', 'j', 'a', 'l']
pas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
How would I find the position of all the 'a' in the codes list. And then print out the corresponding item in the pas list. This is what the output should be. They should also be sorted with the .sort() function.
1
4
8
11
I have come up with this code. (That doesnt work)
qwer = [i for i,x in enumerate(codes) if x == common]
qwe = [qwer[i:i+1] for i in range(0, len(qwer), 1)]
print(pas[qwe])
What would be the best way to get the correct output?
Upvotes: 0
Views: 1002
Reputation: 921
codes = ['a', 'b', 'c', 'a', 'e', 'f', 'g', 'a', 'i', 'j', 'a', 'l']
pas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[pas[index] for index, element in enumerate(codes) if element == "a"]
Upvotes: 0
Reputation: 254
Just added another way to use numpy:
import numpy as np
codes = np.array(['a', 'b', 'c', 'a', 'e', 'f', 'g', 'a', 'i', 'j', 'a', 'l'])
pas = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
index = np.where(codes=='a')
values = pas[index]
In [122]: print(values)
[ 1 4 8 11]
Upvotes: 0
Reputation: 11164
>>> pas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> codes = ['a', 'b', 'c', 'a', 'e', 'f', 'g', 'a', 'i', 'j', 'a', 'l']
>>> result = sorted(i for i,j in zip(pas,codes) if j=='a')
>>> for i in result:
... print i
...
1
4
8
11
Upvotes: 4
Reputation: 48110
There are many ways to achieve it. Your example lists are:
>>> codes = ['a', 'b', 'c', 'a', 'e', 'f', 'g', 'a', 'i', 'j', 'a', 'l']
>>> pas = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Approach 1: Using enumerate
:
>>> indices = [pas[i] for i, x in enumerate(codes) if x == "a"]
indices = [1, 4, 8, 11]
Approach 2: Using zip
:
>>> [p for p, c in zip(pas, codes) if c == 'a']
[1, 4, 8, 11]
Upvotes: 1