簡體   English   中英

在列表中獲取相同的第一個元素並將其分配為python中列表的第一個元素

[英]Taking identical 1st element of a list and assigning it as 1st element of the list in python

我正在嘗試采用相同的列表的第一元素,並將其分配為列表的第一元素。 有人告訴我可以通過使用來自collections模塊的defaultdict來完成,但是有一種方法可以不使用Collections庫來做到這一點。

我有的:

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]]]

您應該使用dict / 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再次使用常規dict:

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

print(d)

使用setdefault時,如果鍵不在dict中,則會添加一個列表作為值,如果它存在,則僅附加值。

您可以在映射中遍歷名稱,然后將其添加到字典中。

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]]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM