查找并从列表中删除重复项,而串联第二个列表

问题描述 投票:0回答:1

我有两个列表,第一个列表包含重复的值。我需要的是删除从List1重复的,也可以作为List2重复值List1合并在同一个指数的值。

我有的:

List1 = ['show1', 'show2', 'show3', 'show2', 'show4', 'show4']
List2 = ['1pm', '10am', '11pm', '2pm', '5pm', '3pm']

我需要的:

List1 = ['show1', 'show2', 'show3', 'show4']
List2 = ['1pm', '10am | 2pm', '11pm', '5pm | 3pm']
python python-3.x
1个回答
4
投票

假设你正在使用Python 3.7+,你可以试试这个:

from collections import defaultdict

List1 = ['show1', 'show2', 'show3', 'show2', 'show4', 'show4']
List2 = ['1pm', '10am', '11pm', '2pm', '5pm', '3pm']

d = defaultdict(list)

for show, time in zip(List1, List2):
    d[show].append(time)

List1 = list(d.keys())
List2 = [' | '.join(times) for times in d.values()]
print(List1)
print(List2)

输出:

['show1', 'show2', 'show3', 'show4']
['1pm', '10am | 2pm', '11pm', '5pm | 3pm']

对于版本低于3.7,可以更换的最后几行本(略多的工作):

List1 = []
List2 = []

for show, times in d.items():
    List1.append(show)
    List2.append(' | '.join(times))
© www.soinside.com 2019 - 2024. All rights reserved.