将函数输出附加到几个列表的Python方法 [英] Pythonic way to append output of function to several lists

查看:118
本文介绍了将函数输出附加到几个列表的Python方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我还没有找到一个好的解决方案。我正在寻找一种更好的方法来将函数输出附加到两个或多个列表,而不使用临时变量。下面的示例:

I have a question that I haven't quite found a good solution to. I'm looking for a better way to append function output to two or more lists, without using temp variables. Example below:

def f():
  return 5,6

a,b = [], []
for i in range(10):
  tmp_a, tmp_b = f()
  a.append(tmp_a)
  b.append(temp_b)

我试过玩zip(* f())之类的东西,但是还不太用这种方式找到了解决方案。
任何删除这些临时变量的方法都将非常有用,谢谢!

I've tried playing around with something like zip(*f()), but haven't quite found a solution that way. Any way to remove those temp vars would be super helpful though, thanks!

编辑其他信息:
在这种情况下,该函数的输出将始终等于要附加的列表的数量。我希望摆脱临时性的主要原因是因为可能有8-10个函数输出,并且具有许多临时性变量会变得混乱(尽管我什至不喜欢拥有两个)。

Edit for additional info: In this situation, the number of outputs from the function will always equal the number of lists that are being appended to. The main reason I'm looking to get rid of temps is for the case where there are maybe 8-10 function outputs, and having that many temp variables would get messy (though I don't really even like having two).

推荐答案

def f():
    return 5,6

a,b = zip(*[f() for i in range(10)])
# this will create two tuples of elements 5 and 6 you can change 
# them to list by type casting it like list(a), list(b)

这篇关于将函数输出附加到几个列表的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆