Python嵌套列表操作

2024-06-16 10:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,python开发人员, 我在玩python列表和Pandas库,在处理列表操作任务时遇到了问题。我想根据每个嵌套列表的索引0处的相同状态名,将所有test\u list[I][0]字典项合并到一个嵌套列表索引中。你知道吗

样本输入:

test_list= [['Alabama', {'Baldwin County': 182265}],
 ['Alabama', {'Barbour County': 27457}],
 ['Arkansas', {'Newton County': 8330}],
 ['Arkansas', {'Perry County': 10445}],
 ['Arkansas', {'Phillips County': 21757}],
 ['California', {'Madera County': 150865}],
 ['California', {'Marin County': 252409}],
 ['Colorado', {'Adams County': 441603}],
 ['Colorado', {'Alamosa County': 15445}],
 ['Colorado', {'Arapahoe County': 572003}]
]

样本输出:

test_list1= [['Alabama', {'Baldwin County': 182265, 'Barbour County': 27457}],
 ['Arkansas', {'Newton County': 8330, 'Perry County': 10445, 'Phillips County': 21757}],
 ['California', {'Madera County': 150865, 'Marin County': 252409}],
 ['Colorado', {'Adams County': 441603, 'Alamosa County': 15445, 'Arapahoe County': 572003}]
]

我已经尝试了很多方法来解决这个问题,但是到目前为止还没有成功。 谢谢你提前帮忙。你知道吗


Tags: test列表newtonlist样本countycaliforniaphillips
2条回答

Python3.5或更高版本

tmp_dict = {}
for lst in test_list:
city = lst[0]
country = lst[1]
if city in tmp_dict:
    tmp_dict[city] = {**tmp_dict[city], **country}
else:
    tmp_dict[city] = country
print(tmp_dict) #you will get dict result
#If you want to get list only
output_result = []
for k in tmp_dict:
    tmp_list.append([k,tmp_dict[k]])
print(output_result) #you will get list result

接近

  • 使用collections.defaultdict作为按公共字段(在本例中为按状态)分组数据的方法。

  • 对于每个状态,defaultdict创建一个新的dict,并用词典更新()方法。

  • 将结果转换回一个列表,其中list应用于字典的项(键/值对)。

工作代码

>>> from pprint import pprint
>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> for state, info in test_list:
        d[state].update(info)

>>> result = list(d.items())
>>> pprint(result)
[('Alabama', {'Baldwin County': 182265, 'Barbour County': 27457}),
 ('Arkansas',
  {'Newton County': 8330, 'Perry County': 10445, 'Phillips County': 21757}),
 ('California', {'Madera County': 150865, 'Marin County': 252409}),
 ('Colorado',
  {'Adams County': 441603, 'Alamosa County': 15445, 'Arapahoe County': 572003})]

相关问题 更多 >