映射列表并替换值

时间:2014-07-29 16:06:39

标签: python list replace

我有两个清单。列表一是

lst1 = ["select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status='Completed' AND ActivityDate = 2014-04-23 AND Owner.Name = OWNERNAME", 
"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status='Completed' AND ActivityDate = 2014-04-22 AND Owner.Name = OWNERNAME", 
"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status='Completed' AND ActivityDate = 2014-04-21 AND Owner.Name = OWNERNAME"] 

列表二是:

lst2 = ['Kyle', 'Jen', 'Batman']

我想将lst1中的OWNERNAME指针替换为lst2中的每个项目。所以我会有一个3 * 3 = 9个元素的列表。我正在尝试使用地图功能:

def replName(string,lst2=['Kyle', 'Jen', 'Batman']):
    for item in lst2:
        string = string.replace('OWNERNAME', item)

finallst = map(replName, lst1)

它不起作用。帮助赞赏。感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用列表推导创建列表:

res = [row.replace("OWNERNAME", name) for name in lst2 for row in lst1 ]

答案 1 :(得分:-1)

假定lst1是实际字符串列表并保留顺序:

final = []

for ind, ele in enumerate(lst1):
    final += [ele.replace("OWNERNAME",x) for x in lst2]
print final

["'select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status='Completed' AND ActivityDate = 2014-04-23 AND Owner.Name = Kyle", "'select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status='Completed' AND ActivityDate = 2014-04-23 AND Owner.Name = Jen", "'select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status='Completed' AND ActivityDate = 2014-04-23 AND Owner.Name = Batman", '"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status="Completed" AND ActivityDate = 2014-04-22 AND Owner.Name = Kyle"', '"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status="Completed" AND ActivityDate = 2014-04-22 AND Owner.Name = Jen"', '"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status="Completed" AND ActivityDate = 2014-04-22 AND Owner.Name = Batman"', '"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status="Completed" AND ActivityDate = 2014-04-21 AND Owner.Name = Kyle"', '"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status="Completed" AND ActivityDate = 2014-04-21 AND Owner.Name = Jen"', '"select Who.ID,Owner.Name,ActivityDate,Type FROM TASK Where Status="Completed" AND ActivityDate = 2014-04-21 AND Owner.Name = Batman"']

保持订单的列表组合:

[ele.replace("OWNERNAME", x)for ele in lst1 for x in lst2  ]

ind是循环遍历lst1的每个元素的索引,因此我们将替换" OWNERNAME"使用lst2

中的名字

发布后,lst1中的语法实际上无效。