0

I have two lists:

l1=['TUDCAPL.CLM_NUM_CD',
    'TUDCAPL.CRT_TS',
    'TUDCAPL.CLM_NUM_CD',
    'TUDCAPL.CRT_TS',
    'TUDCAPJ.CLM_NUM_CD',
    'TUDCAPJ.CRT_TS']

l2 = ['TUDCAPL.CLM_NUM_CD',
      'TUDCAPL.CRT_TS']

I want my result to be

l3 = ['TUDCAPL.CLM_NUM_CD',
      'TUDCAPL.CRT_TS',
      'TUDCAPJ.CLM_NUM_CD',
      'TUDCAPJ.CRT_TS']

I used l3 = [x for x in l1 if x not in l2] but the result is ['TUDCAPJ.CLM_NUM_CD','TUDCAPJ.CRT_TS'] ignoring the duplicates. How can I get the duplicates along with other unique values?

Michael H.
  • 3,323
  • 2
  • 23
  • 31
lpdd
  • 25
  • 2
  • 7

4 Answers4

2

Copy the list (if you do not want to change l1). Loop once over the items in l2 and remove it from the new list. The remove function will discard the first occurrence of each item, leaving the others and the order unaffected.

l1 = ['TUDCAPL.CLM_NUM_CD',
      'TUDCAPL.CRT_TS',
      'TUDCAPL.CLM_NUM_CD',
      'TUDCAPL.CRT_TS',
      'TUDCAPJ.CLM_NUM_CD',
      'TUDCAPJ.CRT_TS']

l2 = ['TUDCAPL.CLM_NUM_CD',
      'TUDCAPL.CRT_TS']

l3 = list(l1)
for x in l2:
    if x in l3:
        l3.remove(x)

from pprint import pprint
pprint(l3)

Result:

['TUDCAPL.CLM_NUM_CD', 
 'TUDCAPL.CRT_TS', 
 'TUDCAPJ.CLM_NUM_CD', 
 'TUDCAPJ.CRT_TS']
Michael H.
  • 3,323
  • 2
  • 23
  • 31
Jongware
  • 22,200
  • 8
  • 54
  • 100
1

You can use a set:

l3 = set(l1)
l3.update(l2)
print l3
Jordan
  • 1,375
  • 14
  • 17
0

I know it's not the best solution but it will keep the order and the unique elements of your list:

from collections import OrderedDict

l1=['TUDCAPL.CLM_NUM_CD',
    'TUDCAPL.CRT_TS',
    'TUDCAPL.CLM_NUM_CD',
    'TUDCAPL.CRT_TS',
    'TUDCAPJ.CLM_NUM_CD',
    'TUDCAPJ.CRT_TS']

l2 = ['TUDCAPL.CLM_NUM_CD',
      'TUDCAPL.CRT_TS']


d = OrderedDict(zip(l1,[None]*len(l1)))
d2 = OrderedDict(zip(l2,[None]*len(l2)))

d.update(d2)
print(d.keys()) # this will contain the resulting list of strings
Gábor Fekete
  • 1,343
  • 8
  • 16
-1

Try to copy your list to a set (this way you get unique values):

l1 = ['TUDCAPL.CLM_NUM_CD', 
      'TUDCAPL.CRT_TS',
      'TUDCAPL.CLM_NUM_CD', 
      'TUDCAPL.CRT_TS', 
      'TUDCAPJ.CLM_NUM_CD', 
      'TUDCAPJ.CRT_TS']
s1 = set(l1)
print(s1)
Michael H.
  • 3,323
  • 2
  • 23
  • 31
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27