1

Here's a list:

foo=[(1, 2, {'weight': 1}), (1, 3, {'weight': 2}), (1, 4, {'weight': 3}), (`1 5, {'weight': 4}), (1, 6, {'weight': 5}), (1, 7, {'weight': 6})]

Say I wanted to extract a particular element of each list within foo and store it in a separate list.

e.g. I wanted to extract 2nd element from each list, within foo and save it in the array labelled bar.

bar=[2,3,4,5,6,7]

How can this be done in Python 2.7x?

2 Answers 2

2
>>> from operator import itemgetter
>>> map(itemgetter(1), foo))
[2, 3, 4, 5, 6, 7]
Sign up to request clarification or add additional context in comments.

Comments

1

You can do that as:

bar = [i[1] for i in foo]
>>> print bar
[2,3,4,5,6,7]

Comments

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.