我有两个列表,第一个列表包含重复的值。我需要的是删除从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 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))