我合并了两个列表,并创建了一个新列表,其中包含两个列表数据,但我正在清理我的嵌套列表。我需要删除重复的键并合并该重复键的值
list1 = [('ID1', 'Name'), ('ID2, 'Name'), ('ID2', 'team')]
expected output should be:
[('ID1', 'Name'), ('ID2, 'Name,team')]发布于 2020-05-18 10:13:32
以下是字典形式的数据,它可能更容易处理:
list1 = [('ID1', 'Name'), ('ID2', 'Name'), ('ID2', 'team')]
# create a dict with empty lists as keys
pivot = {i[0]: [] for i in list1}
for i in list1:
# set the value of the first item key to the second item
pivot[i[0]].append(i[1])
# converted to list of tuples, could be faster without doing the conversion
pivot_tuples = [(k, v) for k, v in pivot.items()]
print(f'dict: {pivot}')
print(f'tupl: {pivot_tuples}')输出:
dict: {'ID1': ['Name'], 'ID2': ['Name', 'team']}
tupl: [('ID1', ['Name']), ('ID2', ['Name', 'team'])]https://stackoverflow.com/questions/61859192
复制相似问题