【问题标题】:Replacing an item of a list by the item of another list if the condition matches如果条件匹配,则用另一个列表的项目替换列表的项目
【发布时间】:2014-05-23 21:01:17
【问题描述】:

假设我有 2 个如下列表。我正在比较两个列表的项目,如果 list1 的第一个项目存在于 list2 的项目中,则将 list1 的项目替换为 list2 的匹配项目,然后从 list2 中删除该项目。然后它应该移动到 list1 的第二项,依此类推。我有以下不正确的代码,但我不知道该怎么做。两个列表中的项目数可能不相同。

list1 = ["abc", "abc", "abc", "xyz", "xyz"]
list2= ["abc123", "abc456", "abc000", "xyz111"]

for i in list1:
    for j in list2:
        if i in j:
            i.replace(i, j)
            list2.remove(j)
            continue
        else:
            continue

结果应该是:

list1 = ["abc123", "abc456", "abc000", "xyz111", "xyz"]

【问题讨论】:

  • 您正在从list2 中删除,同时您正在循环访问它。那总会带来问题。假设您的方法在其他方面是正确的,您可以向后循环或复制它并循环。
  • 另外,整个continue-else-continue 构造似乎完全没有必要。

标签: python


【解决方案1】:

我会为此使用list comprehension[i]zip_longest

from itertools import izip_longest # zip_longest for 3.x

list1 = [b if a in b else a 
         for a, b in izip_longest(list1, list2, fillvalue="")]
list2 = [a for a in list2 if a not in list1]

这会在第一步中保持两个列表之间的索引一致(与 remove 不同),然后清除 list2

【讨论】:

  • 不错的答案。唯一需要更改的是b.startswith(a) 必须是a in b。字符串b 不必以a 开头,它只需要包含它即可。
【解决方案2】:

当您执行for i in list1 时,您将获得列表的元素,而不是列表的位置。

>>> for i in list1:
...    print(type(i))
... 
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

要正常工作,您应该在此处执行类似的操作并就地更改列表

>>> for i in range(len(list1)):
...    print(i)
... 
0
1
2
3
4

【讨论】:

    【解决方案3】:

    这是另一个解决方案:

    >>> list1 = ["abc", "abc", "abc", "xyz", "xyz"]
    >>> list2= ["abc123", "abc456", "abc000", "xyz111"]
    >>>
    >>> [ list2[i] if i < len(list2) and list2[i].startswith(elem) 
    ...   else elem
    ...   for i, elem in enumerate(list1)]
    

    输出:

    ['abc123', 'abc456', 'abc000', 'xyz111', 'xyz']
    

    【讨论】:

      【解决方案4】:

      代码如下:

      >>> for list in list1:
      ...     for a in list2:
      ...         if list in a:
      ...             list1[list1.index(list)] = a
      ...             del list2[list2.index(a)]
      ... 
      >>> 
      >>> print list1
      ['abc123', 'abc000', 'abc456', 'xyz111', 'xyz']
      >>> print list2
      []
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2012-03-12
        • 2022-07-18
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多