0

I have two lists like:

x = ['A','A','A','B','B','C','C','C','D']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']

I wanna remove the duplicates elements of the list, and it can be fulfilled by the answer in Removing elements that have consecutive duplicates

However, the ouput I expect is like

['A','B','C','D']
['0101','0104','0106','0109']

That is

For x, I wanna remove the duplicate elements.

For list_date, I wanna remain the dates based on the remaining elements in x.

Do you have any way to implement this?


2020-06-14 updated:

Thank you for the answers!

My data also has the case

y = ['A','A','A','B','B','C','C','C','D','A','A','C','C','B','B','B']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109','0110','0111','0112','0113','0114','0115','0116']

The output should be

['A','B','C','D','A','C','B']
['0101','0104','0106','0109','0110','0112','0114']

How should I process the list like this?

guavawaga
  • 1
  • 1
  • So you want to remove from ``list_date`` the positions that were removed from ``x``? If you data is linked, is there a reason why you are using two lists instead of one dictionary? – MisterMiyagi Jun 12 '20 at 10:09

3 Answers3

1

You can use zip() to couple your data to your dates, use a loop and a set to remove dupes and zip() again to get single lists from it:

x = ['A','A','A','B','B','C','C','C','D']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']

r = []
k = zip(x,list_date)
s = set()

# go over the zipped values and remove dupes
for el in k:
    if el[0] in s:
        continue
    # not a dupe, add to result and set
    r.append(el)
    s.add(el[0])

data, dates = map(list, zip(*r))

print(data)
print(dates)

Output:

['A', 'B', 'C', 'D']
['0101', '0104', '0106', '0109']

See How to iterate through two lists in parallel?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Try this below :

x = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'D']
    list_date = ['0101', '0102', '0103', '0104', '0105', '0106', '0107', '0108', '0109']
    op = dict()
    y = []
    for i in range(len(x)):
        if x[i] not in y:
            y.append(x[i])
            op[x[i]] = list_date[i]

    z = list(op.values())
    print(y)
    print(z)

Output

['A', 'B', 'C', 'D']
['0101', '0104', '0106', '0109']
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8
0

You Can use zip function to nail this

l = ['A','A','A','B','B','C','C','C','D']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']

new_l = []
new_list_date = []
for i,j in zip(l,list_date):
    if i not in new_l:
        new_l.append(i)
        new_list_date.append(j)
print(new_l)
#['A', 'B', 'C', 'D']
print(new_list_date)
#['0101', '0104', '0106', '0109']


Krishna Singhal
  • 631
  • 6
  • 9