Skip to main content
 首页 » 编程设计

python之如何将二维数组拆分为具有唯一值和字典的数组

2025年05月04日14jpfss

我正在尝试将二维数组拆分为特定格式,但无法确定最后一步。我的数据示例结构如下:

# Original Data 
fileListCode = [['Seq3.xls', 'B08524_057'],  
                ['Seq3.xls', 'B08524_053'],  
                ['Seq3.xls', 'B08524_054'], 
                ['Seq98.xls', 'B25034_001'],  
                ['Seq98.xls', 'D25034_002'],  
                ['Seq98.xls', 'B25034_003']] 

我想把它拆分成这样:

# split into [['Seq3.xls', {'B08524_057':1,'B08524_053':2, 'B08524_054':3}, 
#             ['Seq98.xls',{'B25034_001':1,'D25034_002':2, 'B25034_003':3}] 

字典键 1,2,3 是基于条目的原始位置,从文件名第一次出现开始。为此,我首先制作了一个数组来获取所有唯一的文件名(任何 .xls 都是文件名)

tmpFileList = [] 
tmpCodeList = [] 
arrayListDict = [] 
 
# store unique filelist in a tempprary array: 
for i in range( len(fileListCode)): 
    if fileListCode[i][0] not in tmpFileList: 
        tmpFileList.append( fileListCode[i][0]  ) 

但是,我正在努力进行下一步。我想不出一个好的方法来提取代号(例如 B08524_052),然后将它们转换成带有基于其位置的索引的字典。

# make array to store filelist, and codes with dictionary values 
for i in range( len(tmpFileList)): 
    arrayListDict.append([tmpFileList[i], {}]) 

此代码仅生成 [['Seq3.xls', {}], ['Seq98.xls', {}]] ;我不确定我是否应该先生成结构然后尝试添加代码和字典值,或者是否有更好的方法。

-- 编辑:我只是通过更改 fileListCode

中的值使示例更加清晰

请您参考如下方法:

有了 itertools.groupby 这个过程会简单很多:

>>> key = operator.itemgetter(0) 
>>> grouped = itertools.groupby(sorted(fileListCode, key=key), key=key) 
>>> [(i, {k[1]: n for n, k in enumerate(j, 1)}) for i, j in grouped] 
[('Seq3.xls', {'B08524_052': 1, 'B08524_053': 2, 'B08524_054': 3}), 
 ('Seq98.xls', {'B25034_001': 1, 'B25034_002': 2, 'B25034_003': 3})] 

对于旧的 Python 版本:

>>> [(i, dict((k[1], n) for n, k in enumerate(j, 1))) for i, j in grouped] 
[('Seq3.xls', {'B08524_052': 1, 'B08524_053': 2, 'B08524_054': 3}), 
 ('Seq98.xls', {'B25034_001': 1, 'B25034_002': 2, 'B25034_003': 3})] 

但我认为使用 dict 会更好:

>>> {i: {k[1]: n for n, k in enumerate(j, 1)} for i, j in grouped} 
{'Seq3.xls': {'B08524_052': 1, 'B08524_053': 2, 'B08524_054': 3}, 
 'Seq98.xls': {'B25034_001': 1, 'B25034_002': 2, 'B25034_003': 3}}