【问题标题】:Python: merge two ordered lists, replacing elements conditionallyPython:合并两个有序列表,有条件地替换元素
【发布时间】:2017-08-02 11:28:42
【问题描述】:

初学者的问题。

我有两个相同顺序的有序列表,

list_1=['de', 'de', 'de', '3']
list_2=['6', '5', '3', 'not']

所以 list_1 的第 n 个元素对应于 list_2 的第 n 个元素。

我想合并这两个列表,同时保持它们的顺序。此外,合并产生的列表应该完全由数字组成,即

merged_list=['6', '5', '3', '3']

我最好根据字符串或数值有条件地按列表中的位置进行合并。我对其他有序列表也有同样的问题,但是对于这些列表,我想用字符串值替换数值。 I.a.为了解决我拥有的所有有序列表的问题,我想做类似的事情:

replace element_n of list_i with element_n of list_j if element_n of list_i equals 'z'

其中 z 是数值或字符串值,取决于列表的性质。

【问题讨论】:

    标签: python list python-3.x replace merge


    【解决方案1】:

    您可以使用zip 聚合两个列表项:

    >>> list_1 = ['de', 'de', 'de', '3']
    >>> list_2 = ['6', '5', '3', 'not']
    >>> zip(list_1, list_2)
    <zip object at 0x1029e53c8>
    >>> list(zip(list_1, list_2))
    [('de', '6'), ('de', '5'), ('de', '3'), ('3', 'not')]
    

    str.isdigit 检查给定字符串是否为数字:

    >>> '123'.isdigit()
    True
    >>> 'de'.isdigit()
    False
    

    通过结合conditional expressionlist comprehension,你会得到你想要的:

    >>> [a if a.isdigit() else b for a, b in zip(list_1, list_2)]
    ['6', '5', '3', '3']
    

    【讨论】:

    • 感谢您的帮助。请原谅我的无知,但是 是 Python 输出,而不是命令,对吧?
    • @LucSpan,你是对的。 zip 在 python 3 中返回 zip object..。它是可迭代的,但不显示它的内容。所以我在下一行放了list(zip(..))) 以显示迭代后将产生的项目。
    猜你喜欢
    • 1970-01-01
    • 2019-04-28
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2012-09-07
    相关资源
    最近更新 更多