【问题标题】:Python appending two returns to two different listsPython将两个返回附加到两个不同的列表
【发布时间】:2013-11-09 17:04:26
【问题描述】:

我想将两个返回的列表附加到两个不同的列表中,例如

def func():
    return [1, 2, 3], [4, 5, 6]

list1.append(), list2.append() = func()

有什么想法吗?

【问题讨论】:

  • 你想追加列表[1, 2, 3]本身还是它的项目?
  • 不要把答案放在你的问题中。相反,通过单击勾选接受一个。
  • 我想我可以追加,因为我会将这些输出到 xml 文件中,并且我的函数在循环中运行,我希望每次返回都在单独的行上每个列表中的值位于单独的列中。

标签: python return append


【解决方案1】:

你必须先捕获返回值,然后追加:

res1, res2 = func()
list1.append(res1)
list2.append(res2)

您似乎在这里返回列表,您确定您不是要使用 list.extend() 代替吗?

如果您要扩展 list1list2,则可以使用切片分配:

list1[len(list1):], list2[len(list2):] = func()

但这 a) 令新手感到惊讶,并且 b) 在我看来相当难以理解。我仍然会使用单独的分配,然后扩展调用:

res1, res2 = func()
list1.extend(res1)
list2.extend(res2)

【讨论】:

    【解决方案2】:

    为什么不只存储返回值?

    a, b = func() #Here we store it in a and b
    list1.append(a) #append the first result to a
    list2.append(b) #append the second one to b
    

    有了这个,如果 a 之前是 [10] 并且 b 之前是 [20],你会得到这个结果:

    >>> a, b
    [10, [1,2,3]], [20,[4,5,6]]
    

    不,这并不难,是吗?

    顺便说一句,您可能想要合并列表。为此,您可以使用extend

    list1.extend(a)
    

    希望对你有帮助!

    【讨论】:

      【解决方案3】:

      单行解决方案是不可能的(除非您使用一些神秘的 hack,这总是一个坏主意)。

      你能得到的最好的是:

      >>> list1 = []
      >>> list2 = []
      >>> def func():
      ...     return [1, 2, 3], [4, 5, 6]
      ...
      >>> a,b = func()     # Get the return values
      >>> list1.append(a)  # Append the first
      >>> list2.append(b)  # Append the second
      >>> list1
      [[1, 2, 3]]
      >>> list2
      [[4, 5, 6]]
      >>>
      

      它可读且高效。

      【讨论】:

        猜你喜欢
        • 2014-01-30
        • 2022-11-17
        • 1970-01-01
        • 2011-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        相关资源
        最近更新 更多