Reputation: 969
I would like to have an array with all 2nd elements for which the first element is equal to 'tuple1elem1'. How can I do this efficiently? I have around 500 tuples.
Tuples:
(('tuple1elem1', 'tuple1elem2'), ('tuple2elem1', 'tuple2elem2'), ('tuple3elem1', 'tuple3elem2'))
What I would like to have:
array = ['tuple1elem2']
Upvotes: 1
Views: 17433
Reputation: 764
There is a fast way to get and add only 2nd elements from list of tuples:
import numpy as np
tuples_list = [(0, 10), (0, 20), (0, 30)]
fast_tuples_add = np.array(tuples_list) + (0, 9) # fast tuples add
fast_tuples_add
array([[ 0, 19],[ 0, 29], [ 0, 39]])
Hope this helps
Upvotes: 0
Reputation: 3570
You access elements from a tuple mostly the same way as elements of a list. You could for example unpack them:
>>> bigtuple = (('tuple1elem1', 'tuple1elem2'), ('tuple2elem1', 'tuple2elem2'), ('tuple3elem1', 'tuple3elem2'))
>>> array = [ele2 for ele1, ele2 in bigtuple if ele1 == "tuple1elem1"]
['tuple1elem2']
Upvotes: 1
Reputation: 75545
Use a list comprehension with a filter.
myList = [...]
output = [x[1] for x in myList if x[0] == 'tuple1elem1']
Upvotes: 7