Pythonic way to append output of function to several lists(将函数输出附加到多个列表的 Pythonic 方法)
问题描述
我有一个问题,我还没有找到很好的解决方案.我正在寻找一种更好的方法来将函数输出附加到两个或更多列表,而不使用临时变量.示例如下:
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)
这篇关于将函数输出附加到多个列表的 Pythonic 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将函数输出附加到多个列表的 Pythonic 方法
基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
