-4

I am trying to merge two lists where the values differ by the last 3 digits.

Input list 1:

['YTS0R000', 'YTS1R000', 'YTS2R000']

Input list 2:

['YTS0R101', 'YTS5R101', 'YTS2R101']

Desired output:

['YTS0R000', 'YTS1R000', 'YTS5R101', 'YTSR000']

I've tried

for input in Final_1_out:
    for input2 in Final_1_in:
        if input[-3:]!=input2[-3:]:
            Final_in_out.append((input))

but I am getting duplicate entries

Timus
  • 10,974
  • 5
  • 14
  • 28
S SUBHASH
  • 1
  • 4
  • 1
    Please update your question containing the input data and the desired output. – Cow Aug 12 '22 at 05:47
  • input list 1 'YTS0R000','YTS1R000','YTS2R000' Input List 2 'YTS0R101','YTS5R101,'YTS2R101' OUTPUT: 'YTS0R000','YTS1R000','YTS5R101','YTS2R000' – S SUBHASH Aug 12 '22 at 05:52
  • Aside: Don't use `input` as a variable name, you're overriding a builtin function. – Timus Aug 12 '22 at 10:37

1 Answers1

0

Just convert the lists to a dict where the key is the string but the last 3 digits and the value is the string itself. And then use the union operator to merge them. Then, convert back to list using dict.values().

merged_lists = list((
  {item[0:-3]:item for item in Final_1_in} |
  {item[0:-3]:item for item in Final_1_out}
).values())

Output:

['YTS0R000', 'YTS5R101', 'YTS2R000', 'YTS1R000']
lepsch
  • 8,927
  • 5
  • 24
  • 44
  • input list 1 'YTS0R000','YTS1R000','YTS2R000' Input List 2 'YTS0R101','YTS5R101,'YTS2R101' OUTPUT: 'YTS0R000','YTS1R000','YTS5R101','YTS2R000 – S SUBHASH Aug 12 '22 at 05:56
  • I've edited the answer with a new solution given the output. It works if the output order doesn't matter. – lepsch Aug 12 '22 at 06:22