I have a list made of lists like :
values = [('Part A', 0.1), ('Part B', 0.2), ('Part C', 0.3)]
How can I take only the second element from all the lists within the values list without using a "for" loop?
By using the brackets []
values[0][1]
It outputs the 0.1 value. But when I do
values[:][1]
It outputs both parts of the first list.
Sorry I am a beginner.
CodePudding user response:
One way is using list comprehension
[item[1] for item in values]
Another way is using numpy array
np.array(values)[:,1]
CodePudding user response:
You can use itemgetter
to extract a specific item from an object. [list, tuple, dictionary]
itemgetter
takes as input an index or a set of indices
Code:
import operator
values = [('Part A', 0.1), ('Part B', 0.2), ('Part C', 0.3)]
all_elements=list(map(operator.itemgetter(0,1),values))
second_elements = list(map(operator.itemgetter(1), values))
print(all_elements) #[('Part A', 0.1), ('Part B', 0.2), ('Part C', 0.3)]
print(second_elements) #[0.1, 0.2, 0.3]