0

I have two lists, the first list contains duplicate values. What I need is to remove the duplicates from List1 and also merge the values in List2 on the same indices as List1 duplicate values.

What I Have:

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

What I Need:

List1 = ['show1', 'show2', 'show3', 'show4']
List2 = ['1pm', '10am | 2pm', '11pm', '5pm | 3pm']
Ali Hassan
  • 75
  • 7

1 Answers1

4

Assuming you are using Python 3.7+, You can try this:

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)

Output:

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

For version less than 3.7, you can replace the last few lines with this (slightly more work):

List1 = []
List2 = []

for show, times in d.items():
    List1.append(show)
    List2.append(' | '.join(times))
iz_
  • 15,923
  • 3
  • 25
  • 40
  • You should note that the order of `List1` is not guaranteed in many versions of Python (before 3.6, 3.6 for anything not CPython). – Rory Daulton Feb 02 '19 at 21:12
  • Adding to what @RoryDaulton said regarding `defaultdict.keys()` not preserving sort order for pre-3.6 Python versions, that problem is discussed here: https://stackoverflow.com/questions/31770251/defaultdict-on-append-elements-maintain-keys-sorted-in-the-order-of-addition – Kate Feb 02 '19 at 21:20
  • @RoryDaulton - for clarity, I assume you are referring to the order of `List1` after it is mutated into a list of the `defaultdict` keys (not the order of the first initialized list). – benvc Feb 02 '19 at 21:20
  • @benvc Correct, this answer wont preserve the original order of the items in `List1` because `defaultdict.keys()` doesn't guarantee order in pre-3.6 Python versions (as @RoryDaulton pointed out). – Kate Feb 02 '19 at 21:21
  • @RoryDaulton I added a more version-friendly solution. – iz_ Feb 02 '19 at 21:24