2016-07-27 255 views
0

我想將列表中的第一個元素取爲相同的第一個元素並將其指定爲列表的第一個元素。我被告知它可以通過使用默認集合模塊完成,但有沒有一種方法可以做到這一點,而不使用集合庫。採取相同的第一個元素的列表,並將其指定爲python列表的第一個元素

我有:

mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]] 

我所期待的事:

mapping = [['Tom',[ 'BTPS 1.500 625', 0.702604], [ 'BTPS 2.000 1225', 0.724939]],['Max',[ 'OBL 0.0 421', 0.766102],['DBR 3.250 721', 0.887863]]] 

回答

1

您應該按名稱使用字典/defaultdict對數據進行分組,使用的第一個元素,其是作爲名稱的關鍵,將其餘數據切片並附加爲數值:

from collections import defaultdict 

d = defaultdict(list) 
for sub in mapping: 
    d[sub[0]].append(sub[1:]) 

print(d) 

這將使你:

defaultdict(<type 'list'>, {'Max': [['OBL 0.0 421', 0.766102], ['DBR 3.250 721', 0.887863]], 'Tom': [['BTPS 1.500 625', 0.702604], ['BTPS 2.000 1225', 0.724939]]}) 

或訂單問題,使用OrderedDict

from collections import OrderedDict 

d = OrderedDict() 
for sub in mapping: 
    d.setdefault(sub[0],[]).append(sub[1:]) 

這就給了你:

OrderedDict([('Tom', [['BTPS 1.500 625', 0.702604], ['BTPS 2.000 1225', 0.724939]]), ('Max', [['OBL 0.0 421', 0.766102], ['DBR 3.250 721', 0.887863]])]) 

沒有任何進口,只是使用普通的字典再次使用dict.setdefault

d = {} 
for sub in mapping: 
    d.setdefault(sub[0],[]).append(sub[1:]) 

print(d) 

使用setdefault,如果鍵不在字典中,它會添加一個列表作爲值,如果它存在,它只是附加值。

+0

感謝Padraic提供瞭如此快速的響應。有沒有必要導入收集模塊? –

+0

@Ghale-Boong,是的,我會編輯 –

0

您可以遍歷映射中的名稱並添加到字典中。

mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]] 

#using dictionary to store output 
mapping_dict=dict() 

for items in mapping: 
if items[0] in mapping_dict: 
    mapping_dict[items[0]].append([items[1],items[2]]) 
else: 
    mapping_dict[items[0]]=[items[1],items[2]] 

print mapping_dict 

Output: {'Max': ['OBL 0.0 421', 0.766102, ['DBR 3.250 721', 0.887863]], 'Tom': ['BTPS 1.500 625', 0.702604, ['BTPS 2.000 1225', 0.724939]]} 
相關問題