【问题标题】:Searching through a list of lists?搜索列表列表?
【发布时间】:2013-10-28 17:30:51
【问题描述】:

我对 python 有点陌生,我有一个问题。我有一堆单词存储在列表列表中,如下所示:

[["Hello", "my", "name", "is", "world"], ["Hello", "World!"]]

我还有另一个列表,其中包含这样的单词列表:

["Hello", "name"]

我想比较第二个列表是否有列表列表中的任何单词,如果有,请将列表列表中的单词替换为另一个单词。在我们的示例中,Helloname 将被替换为:

[["replaced", "my", "replaced", "is", "world], ["replaced", "World!"]]

如果有人可以帮助我,那就太好了!谢谢!我只是不确定如何访问列表元素的列表。

【问题讨论】:

    标签: python string list replace


    【解决方案1】:

    使用列表推导和设置:

    >>> lis = [["Hello", "my", "name", "is", "world"], ["Hello", "World!"]]
    >>> lis2 = ["Hello", "name"]
    >>> s = set(lis2)           #if lis2 is huge
    >>> [[x if x not in s else 'replaced' for x in item] for item in lis]
    [['replaced', 'my', 'replaced', 'is', 'world'], ['replaced', 'World!']]
    

    【讨论】:

      【解决方案2】:

      列表理解方法可能是完成任务的最 Pythonic/优雅的方式。但是,如果您更喜欢就地替换方法(而不是生成新列表),您可以这样做:

      数据定义:

      data = [["Hello", "my", "name", "is", "world"], ["Hello", "World!"]]
      check = ["Hello", "name"]
      

      备选方案 1:

      for i, lst in enumerate(data):
          for j, word in enumerate(lst):
              if word in check: data[i][j] = 'replaced'
      

      备选方案 2:

      for i in xrange(len(data)):
          for j in xrange(len(data[i])):
            if data[i][j] in check: data[i][j] = 'replaced'
      

      如果列表很大且替换很少,我想这种方法更节省资源,因为与从头开始生成新列表相比,进行就地替换需要更少的时间和更少的内存(同时进行相同数量的迭代/比较/查找)。

      【讨论】:

        猜你喜欢
        • 2020-06-26
        • 2010-12-04
        • 2011-08-01
        • 2021-05-15
        • 2017-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多