Python - 如何用另一个列表中的字符串值替换列表中存储的字符串的值?

时间:2016-11-17 11:47:14

标签: python arrays string replace

我有搜索堆栈溢出并搜索了解决此问题的解决方案,遗憾的是我无法找到解决方案。

我想用另一个列表中的字符串值替换列表中存储的字符串的值。

例如,我有两个列表:

list_a = ['file_x', 'file_x', 'file_x', 'file_x']
list_b = ['1', '2', '3', '4']

我希望结果返回:

list_c =['file_1', 'file_2', 'file_3', 'file_4']

我是python的新手,我正在努力做到这一点,我尝试使用for循环和str.replace(),但我不知道如何匹配每个数组的键值并替换'x' list_a的每个元素,其中包含list_b元素的字符串值。

对此的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:7)

使用zip将相应的 var meetingsEditorParams = { tools: ['bold', 'italic', 'underline', 'strikethrough', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'insertUnorderedList', 'insertOrderedList', 'indent', 'outdent', 'createTable', 'addRowAbove', 'addRowBelow', 'addColumnLeft', 'addColumnRight', 'deleteRow', 'deleteColumn', 'formatting' ,'pdf'], stylesheets: ["../../../../Content/css/pdf-export-styles.css"], pdf: { fileName: "RECAP-TO-PRINT : " + self.fileName + ".pdf", paperSize: "a4", margin: { bottom: 20, left: 20, right: 20, top: 20 } }, pdfExport: function (e) { //add the header to the original content and export it self.meetingEditor.value("Header To Insert" + self.Content()); // go back to the original content after the export e.promise.done(self.meetingEditor.value(self.Content())); } , change: function (e) { console.log(self.meetingEditor.value()); self.Content(self.meetingEditor.value()); } }; self.meetingEditor = $("#meetingEditor").kendoEditor(meetingsEditorParams).data("kendoEditor"); protected void Page_Load(object sender, EventArgs e) { var form = (HtmlForm)this.Master.FindControl("form1"); form.Action = "http://blarg.com"; } 联系起来。

a

我们可以在for循环中轻松使用此 b对象,将对解包为单独的变量>>> list(zip(list_a, list_b)) [('file_x', '1'), ('file_x', '2'), ('file_x', '3'), ('file_x', '4')] zip,然后执行{{1并将结果值附加到结果列表中:

a

这也可以写成短名单理解:

b

正如Moinuddin指出的那样,如果您定义了a.replace('x', b)

的内容,那么在这里使用格式字符串是更好的选择

答案 1 :(得分:3)

如果您是创建list_a格式的人。更好的方法是使用{}代替x,并使用str.format()格式化字符串。例如:

>>> list_a = ['file_{}', 'file_{}', 'file_{}', 'file_{}']
>>> list_b = ['1', '2', '3', '4']
>>> [a.format(b) for a, b in zip(list_a, list_b)]
['file_1', 'file_2', 'file_3', 'file_4']