【问题标题】:Python - How do you replace the values of strings stored in a list with the string values from another list?Python - 如何用另一个列表中的字符串值替换存储在列表中的字符串值?
【发布时间】:2017-03-31 22:45:18
【问题描述】:

我有搜索堆栈溢出,并在谷歌上搜索了这个问题的解决方案,不幸的是我无法找到解决方案。

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

例如我有两个列表:

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 元素的字符串值。

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

【问题讨论】:

    标签: python arrays string replace


    【解决方案1】:

    使用zip 耦合对应的as 和bs。

    >>> list(zip(list_a, list_b))
    [('file_x', '1'), ('file_x', '2'), ('file_x', '3'), ('file_x', '4')]
    

    我们可以在 for 循环中轻松使用这个 zip 对象,将这些对解压缩为单独的变量 ab,然后执行 a.replace('x', b) 并将结果值附加到我们的结果列表:

    >>> list_c = []
    >>> for a, b in zip(list_a, list_b):
    ...    list_c.append(a.replace('x', b))
    ...
    >>> list_c
    ['file_1', 'file_2', 'file_3', 'file_4']
    

    这也可以写成一个简短的列表理解:

    >>> [a.replace('x', b) for a, b in zip(list_a, list_b)]
    ['file_1', 'file_2', 'file_3', 'file_4']
    

    正如 Moinuddin 指出的那样,如果您定义了 list_a 的内容,则在此处使用 格式字符串 是一个更好的选择

    【讨论】:

    • 谢谢!这确实不仅帮助解决了问题,还教会了我一种处理数组的新方法。
    • @Lewis909 他们是名单:D
    • 谢谢,因为 Python 没有数组,它有列表。
    【解决方案2】:

    如果您是创建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']
    

    【讨论】:

    • 我会看一下str.format()。这与 str.replace() 有何不同?
    • str.replace('x') 将替换所有出现的x,即使它是字符串的一部分。 {} 将把你的价值放在{} 的位置。
    • @Lewis909 请注意,您的字符串也可以包含文字 {}(您只需在格式字符串中将它们加倍;'The string can contain {{ and }}, and only this {} here will be substituted'.format(value)
    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2012-08-18
    • 2021-08-02
    • 2013-12-31
    相关资源
    最近更新 更多