【问题标题】:Create lists python [closed]创建列表python [关闭]
【发布时间】:2014-05-26 19:33:13
【问题描述】:

我需要在 python 中的函数内构建如此多的列表,以指示作为其参数之一给出的函数的参数,这是一个正整数。我如何在 python 中通过循环或列表理解来做到这一点?

【问题讨论】:

  • 不清楚你在问什么。给定一个数字n 作为参数,你想创建一个n 列表的列表吗?
  • 你的意思是for i in range(0, input): list()

标签: python list function list-comprehension


【解决方案1】:

我相信这会做你想要的:

def makelists(list_count):
    list_of_lists = []
    for _ in range(list_count):
        list_of_lists.append(list())
    return list_of_lists

或者使用列表理解:

def makelists(list_count):
    return [[] for _ in range(list_count)]

如果您使用的是 Python 2,请使用 xrange(在 2 中,它会避免在内存中创建完整的列表 range。)例如:

def makelists_py2(list_count):
    return [[] for _ in xrange(list_count)]

我使用_ 作为一次性变量,因为range(和xrange)都返回我们不使用的递增整数。

【讨论】:

  • 你的意思是[[] for _ in xrange(list_count)]
  • 关闭,xrange 仅适用于 Python 2,但 range 在 2 和 3 中都适用,如果 2 次优。
【解决方案2】:

你的意思是这样的:

def make_lists(n):
   return [[] for _ in range(n)]

这会创建一个n 空列表的列表。

【讨论】:

    【解决方案3】:

    你可以[[]] * n。这完全符合您的要求,但可能与您预期的不同:

    >>> my_list = [[]] * 7
    >>> my_list
    [[], [], [], [], [], [], []]
    >>> my_list[0].append('foo')
    >>> my_list
    [['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo']]
    

    【讨论】:

    • @YábirGarcia 它并没有像你想象的那样做,它们都是同一个列表,所以编辑一个会编辑它们。
    • 旁注,对于一个错误的给定答案,这里的标准协议是什么,但一个有趣的花絮来自为什么它是错误的?我是否将答案留在 cmets 中,还是将其删除?
    • @BradBeattie 由你决定。您的回答没有错,因为 OP 不够具体。但是,您的答案也不是大多数用户认为 OP 正在寻找的答案
    猜你喜欢
    • 2019-03-29
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2013-08-08
    • 2018-11-09
    • 2018-04-13
    相关资源
    最近更新 更多