【问题标题】:Python: Complete list with itemsPython:包含项目的完整列表
【发布时间】:2014-07-30 21:34:20
【问题描述】:

假设我有很多列表。这些列表中的每一个都可能具有不同的长度。我想做的是用(例如)字符串“EMPTY”来完成每个列表。是否有内置函数或非常简单的命令集可以提供该功能?

我认为在 2 个 for 循环中是可能的。

for list in lists:
    for i in range(0,10):
        try:
            val = list[i]
        except IndexError:
            // list[i] = "EMPTY" 
            list.append("EMPTY")

每个使用 Python 的人都知道,Python 有大量的小功能可以处理字符串、列表等......所以我的问题是是否有更简单的方法。

例如:

for list in lists:
    list.complete("EMPTY",10)

【问题讨论】:

  • 如果您这样做是因为您想同时迭代多个列表,请查看this answer

标签: python list syntax


【解决方案1】:

有很多方法。这是一个,但我不假装这是唯一的方法:

def complete(lst, fill_value, desired_length):
    return lst + [fill_value] * (desired_length - len(lst))

如果您的 fill_value 是可变的,例如列表或字典,那是不安全的,但字符串没问题。

此外,它返回一个新列表,而不是编辑提供的列表。如果你想编辑它:

def complete(lst, fill_value, desired_length):
    return lst.extend([fill_value] * (desired_length - len(lst)))

【讨论】:

    【解决方案2】:
    for alist in lists:
        alist.extend(["EMPTY"]*(10-len(alist))
    

    也许?作为完成此任务的众多方法之一...

    【讨论】:

      【解决方案3】:

      我确信有很多方法可以做到这一点,但这是我首先想到的:

      def complete_lists(lists, length, filler):
          for lst in lists: #btw, don't use list as a variable name
              lst.extend([filler for i in range(len(lst), length)])
      

      你也可以在一个可怕的单线里做这件事以获得乐趣:

      def complete_lists(lists, length, filler):
          __ = [lst.extend([filler for i in range(len(l), length)]) for lst in lists]
      

      【讨论】:

        【解决方案4】:

        嗯,可能会短一点

        n = 10 
        for l in lists:
            l.extend((("EMPTY "*(n-len(l))).split())
        

        【讨论】:

        • 请不要鼓励人们使用list作为变量名
        【解决方案5】:

        使用fillvalue 参数到itertools.iziplongest 很容易做到这一点

        首先导入必要的模块并创建数据:

        >>> import pprint
        >>> import itertools
        >>> lists = (list('abc'), list('defg'), list('hijkl'))
        >>> lists
        (['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j', 'k', 'l'])
        

        现在,我们可以根据最长的列表压缩它们,并使用所需的填充值:

        >>> pprint.pprint(list(itertools.izip_longest(*lists, fillvalue='EMPTY')))
        [('a', 'd', 'h'),
         ('b', 'e', 'i'),
         ('c', 'f', 'j'),
         ('EMPTY', 'g', 'k'),
         ('EMPTY', 'EMPTY', 'l')]
        

        最后,演示转置列表以获得所需的最终结果:

        >>> pprint.pprint(list(zip(*itertools.izip_longest(*lists, fillvalue='EMPTY'))))
        [('a', 'b', 'c', 'EMPTY', 'EMPTY'),
         ('d', 'e', 'f', 'g', 'EMPTY'),
         ('h', 'i', 'j', 'k', 'l')]
        

        【讨论】:

          【解决方案6】:

          您可能更喜欢将 None(而不是字符串)附加到您的列表中。

          例如,用:

          def completeList(lst):
              while len(lst) < 10:
                  lst.append(None)
              return lst
          

          您可以执行以下操作:

          for lst in lists:
              lst = completeList(lst)
          

          这会变成这样:

          lists = [[1, 2, 4], 
                   ['one', 'two', 'three', 'four', 'five'], 
                   ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']]
          

          进入:

          Out: [[1, 2, 4, None, None, None, None, None, None, None],
                ['one', 'two', 'three', 'four', 'five', None, None, None, None, None],
                ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']]
          

          使用 None 只会稍微提高效率,但可能会允许您稍后在代码中对列表执行更直接的操作。例如,在字符串 'EMPTY' 不会的情况下, None 将评估为 false。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-12-28
            • 2018-07-07
            • 1970-01-01
            • 1970-01-01
            • 2020-04-03
            • 1970-01-01
            • 2011-05-26
            • 1970-01-01
            相关资源
            最近更新 更多