【问题标题】:I have two lists. list1 as keys, list2 as values. How to appendix a list of values to the same keys in the list1?我有两个清单。 list1 作为键,list2 作为值。如何将值列表附加到 list1 中的相同键?
【发布时间】:2020-08-03 12:08:01
【问题描述】:

list1 = [A,A,A,B,B,B,C,C,C] list2 = [1,2,3,4,5,6,7,8,9]

预期输出:{A:[1,2,3],B:[4,5,6],C:[7,8,9]}

这就是我想做的。但是,当我附加不同的值列表时,我陷入了困境。 这是我的代码:

g = []
for i in range(len(list1)-1):
    if list1[i] == list1[i+1]:
        g.append(list2[i+1])
    else:
        continue
print(g)

输出为:[1,2,3,5,6,8,9]。我该怎么做才能获得单独的列表为 [1,2,3],[4,5,6],[7,8,9]?

【问题讨论】:

  • 欢迎来到 SO!关于措辞,我相信您实际上是在寻找基于两个列表的地图。如果这是正确的,我建议您在提供示例之前解释您希望如何构建地图。此外,如果您针对特定语言,您可以在标签中提及它

标签: list loops dictionary


【解决方案1】:

用字典试试下面这个:

list1 = ['A','A','A','B','B','B','C','C','C']
list2 = [1,2,3,4,5,6,7,8,9]

output = {}
for i in range(len(list1)):
    if list1[i] not in output:
        output[list1[i]] = [list2[i]]
    else:
        output[list1[i]].append(list2[i])

print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2021-04-27
    • 2023-03-23
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多