[Python] Modify elements of a list based on another list

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have two lists that look like -

    list_a = [('gfhr_10_dfrght_sl', None, None), ('gfhr_11_dfrght_sl', None, None), ('mnop_yxt_done', None, None), ('mnop_yxt_gd', None, None), ('frdf_yxty_syn', None, None), ('ABC_XYZ1', 2, 0), ('ABC_XYZ2', 2, 0), ('ABC_XYZ3', 2, 0), ('ABC_XYZUL', 2, 0), ('ABC_JKL1', 1, 0), ('ABC_JKL2', 1, 0)]


    list_b = ['ABC_XYZ1', 'ABC_XYZ2', 'ABC_XYZ3', 'ABC_XYZUL', 'mnop_yxt_done', 'mnop_yxt_gd', 'frdf_yxty_syn', 'ABC_JKL1', 'ABC_JKL2', 'DFG_OUT2_ATTgd', 'UHBCB_DFG_nvbgh']


    I want a list_c that looks like -

    list_c = ['(2-0) ABC_XYZ1', ' (2-0) ABC_XYZ2', '(2-0) ABC_XYZ3', '(2-0) ABC_XYZUL', 'mnop_yxt_done', 'mnop_yxt_gd', 'frdf_yxty_syn', '(2-0) ABC_JKL1', '(2-0) ABC_JKL2', 'DFG_OUT2_ATTgd', 'UHBCB_DFG_nvbgh']


    Basically it should replace items in list_b from items and corresponding index that are present in list_a. I have this code -

    for i in list_b:
    for j in list_a:
    if (i == j[0]) and (j[1] != 'None'):
    list_c.append(f"({j[1]}-{j[2]}) {i}")
    else:
    list_c.append(i)
    list_c = list(dict.fromkeys(list_c))
    print(list_c)


    I am getting this output instead -

    ['ABC_XYZ1', '(2-0) ABC_XYZ1', 'ABC_XYZ2', '(2-0) ABC_XYZ2', 'ABC_XYZ3', '(2-0) ABC_XYZ3', 'ABC_XYZUL', '(2-0) ABC_XYZUL', 'mnop_yxt_done', '(None-None) mnop_yxt_done', 'mnop_yxt_gd', '(None-None) mnop_yxt_gd', 'frdf_yxty_syn', '(None-None) frdf_yxty_syn', 'ABC_JKL1', '(1-0) ABC_JKL1', 'ABC_JKL2', '(1-0) ABC_JKL2', 'DFG_OUT2_ATTgd', 'UHBCB_DFG_nvbgh']


    It's appending same element again too in my code. How do I just get it once?

    Continue reading...

Compartilhe esta Página