2014-03-27 16 views
0

這個問題是我當前問題的一部分,所以讓我們從大局開始。在Python列表中爲每個元組的特定位置提取變量

我想按降序排列字典的值。我的字典是1對1對應的,如:

( 'ID1':值1, 'ID2':值2,......)

我跟着this thread和找到我的回答:

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

然後我試圖提取鍵在sorted_dict,因爲我認爲這是一個dictionary。但是,事實證明sorted_dictlist,因此沒有keys()方法。

事實上,sorted_dict被組織爲:

[( 'ID1',值1),( 'ID2',值2),...]#一個元組

組成列表

但我需要的是IDS,如清單:

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

所以現在,問題轉到如何從列表中的每個元組提取特定位置的變量?

有什麼建議嗎?謝謝。

+0

看一看OrderedDict:http://docs.python.org/2/library/collections.html#collections.OrderedDict – Don

回答

3

你可以做到這一點使用list comprehension如下:

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

這得到各tuple的第一個元素的元組

1

使用列表理解的sorted_dict列表:

[i for (i,_) in sorted_dict] 

應解決你的問題

0

使用mapitemgetter來處理列表,並獲得的第一個元素

import operator 
first_elements = map(operator.itemgetter(0), sorted_list) 
相關問題