简体   繁体   中英

Extract variable at specific position for each tuple in a Python list

This question is a part of my current problem, so let's start with the big picture.

I am trying to sort a dictionary by the values in descending order. My dictionary is 1-to-1 corresponding, such as:

('ID1':value1, 'ID2':value2, ......)

I followed this thread and find my answer:

import operator
sorted_dict = sorted(original_dict.iteritems(), key = operator.itemgetter(1), reverse = True)

Then I tried to extract the keys in sorted_dict since I thought it is a dictionary . However, it turns out that sorted_dict is a list , thus has no keys() method.

In fact, the sorted_dict is organized as:

[('ID1', value1), ('ID2', value2), .....] # a list composed of tuples

But what I need is a list of ids such as:

['ID1', 'ID2', ......]

So now, the problem turns to How to extract variable in specific position for each of the tuples in a list?

Any suggestions? Thanks.

You can do that using list comprehension as follows:

>>> ids = [element[0] for element in sorted_dict]
>>> print ids
['ID1', 'ID2', 'ID3', ...]

This gets the first element of each tuple in the sorted_dict list of tuples

Using list comprehension:

[i for (i,_) in sorted_dict]

should solve your problem

Use map plus itemgetter to process a list and get the first element

import operator
first_elements = map(operator.itemgetter(0), sorted_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM