且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Python 中将多个变量附加到列表中

更新时间:2022-11-19 17:21:57

您可以使用 extend 将任何可迭代对象附加到列表中:

You can use extend to append any iterable to a list:

vol.extend((volumeA, volumeB, volumeC))

根据你的变量名的前缀对我来说有一种不好的代码味道,但你可以做到.(附加值的顺序未定义.)

Depending on the prefix of your variable names has a bad code smell to me, but you can do it. (The order in which values are appended is undefined.)

vol.extend(value for name, value in locals().items() if name.startswith('volume'))

如果顺序很重要(恕我直言,仍然闻起来不对):

If order is important (IMHO, still smells wrong):

vol.extend(value for name, value in sorted(locals().items(), key=lambda item: item[0]) if name.startswith('volume'))