简体   繁体   中英

Replace items in a Python list from another list

Lets say I have two lists,

l1 = ['Join', 'logsource1.selection1', 'and', 'logsource2.selection3', 'AND', '((logsource1.selection2', '<=', 'contraint1)', 'AND', '(logsource2.selection4', '<=', 'constraint1))']
l2 = ['logsource1=Zscaler/Proxy', 'logsource2=Proofpoint/TAP']

How do I take the values from l2 and replace in l1, something like this,

l3 = ['Join', 'Zscaler/Proxy.selection1', 'and', 'logsource2=Proofpoint/TAP.selection3', 'AND', '((Zscaler/Proxy.selection2', '<=', 'contraint1)', 'AND', '(Proofpoint/TAP.selection4', '<=', 'constraint1))']

Try:

l2 = list(map(lambda x: x.split("="), l2))

def func(arr, el):
    if(len(el)==0):
        return list(arr)
    else:
        return func(map(lambda x: x.replace(*el[0]), arr), el[1:])

l1=func(l1, l2)

Outputs:

>>> l1

['Join', 'Zscaler/Proxy.selection1', 'and', 'Proofpoint/TAP.selection3', 'AND', '((Zscaler/Proxy.selection2', '<=', 'contraint1)', 'AND', '(Proofpoint/TAP.selection4', '<=', 'constraint1))']

Using a helping dictionary should do the trick:

l1 = ['Join', 'logsource1.selection1', 'and', 'logsource2.selection3', 'AND', '((logsource1.selection2', '<=', 'contraint1)', 'AND', '(logsource2.selection4', '<=', 'constraint1))']
l2 = ['logsource1=Zscaler/Proxy', 'logsource2=Proofpoint/TAP']

l_help = {split_result[0]: split_result[1] for split_result in [e.split("=") for e in l2]}

l3 = l1.copy()

for key, value in l_help.items():
    l3 = [e.replace(key, value) for e in l3]

Output is:

['Join', 'Zscaler/Proxy.selection1', 'and', 'Proofpoint/TAP.selection3', 'AND', '((Zscaler/Proxy.selection2', '<=', 'contraint1)', 'AND', '(Proofpoint/TAP.selection4', '<=', 'constraint1))']

You can try with this

l1 = ['Join', 'logsource1.selection1', 'and', 'logsource2.selection3', 'AND', '((logsource1.selection2', '<=', 'contraint1)', 'AND', '(logsource2.selection4', '<=', 'constraint1))']
l2 = ['logsource1=Zscaler/Proxy', 'logsource2=Proofpoint/TAP']
l3=[]
for i in l1:
    for j in l2:
        k,v=j.split("=")
        if k in i:
            l3.append(i.replace(k,v))
            break
    else:
        l3.append(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM