简体   繁体   English

Python 列表中的条件替换

[英]Conditional replace in a Python list

The actual values are in a dictionary something like this,实际值在字典中,如下所示,

{'logsource1': {'product': 'ABC', 'service': 'Proxy'},
 'logsource2': {'product': 'DEF', 'service': 'Proxy'},
 'condition': 'Join logsource1.selection1 and logsource2.selection3 AND ((logsource1.selection2 <= contraint1) AND (logsource2.selection4 <= constraint1))',
  'constraint1': {'Value': '5 minutes', 'Type': 'Datetime'}}}

l1 = ['Join', 'logsource1.selection1', 'and', 'logsource2.selection3', 'AND', '((logsource1.selection2', '<=', 'contraint1)', 'AND', '(logsource2.selection4', '<=', 'constraint1))']

I extracted the condition and added it to list l1 so that the find and replace would be easier.我提取了条件并将其添加到列表 l1 中,以便查找和替换更容易。 Similarly the actual values to be replaced with are also part of the same dictionary.同样,要替换的实际值也是同一个字典的一部分。

the output should be, output 应该是,

l1 = ['Join', 'ABC.selection1', 'and', 'DEF.selection3', 'AND', '((ABC.selection2', '<=', 'contraint1)', 'AND', '(DEF.selection4', '<=', 'constraint1))'] l1 = ['Join', 'ABC.selection1', 'and', 'DEF.selection3', 'AND', '((ABC.selection2', '<=', 'contraint1)', 'AND', ' (DEF.selection4', '<=', 'constraint1))']

Assuming you have the values stored in a dictionary:假设您将值存储在字典中:

values = {
    'logsource1.selection1': 'foo',
    'logsource2.selection3': 'bar',
     # etc
}

Then you can iterate over the list positions and substitute:然后您可以遍历列表位置并替换:

for i in range(len(l1)):
    if l1[i] in values:
        l1[i] = values[l1[i]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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