将几个变量附加到 Python 中的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14860460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append several variables to a list in Python
提问by ustroetz
I want to append several variables to a list. The number of variables varies. All variables start with "volume". I was thinking maybe a wildcard or something would do it. But I couldn't find anything like this. Any ideas how to solve this? Note in this example it is three variables, but it could also be five or six or anything.
我想将几个变量附加到一个列表中。变量的数量各不相同。所有变量都以“volume”开头。我在想也许通配符或其他东西可以做到。但我找不到这样的东西。任何想法如何解决这个问题?请注意,在此示例中,它是三个变量,但也可以是五个或六个或任何其他变量。
volumeA = 100
volumeB = 20
volumeC = 10
vol = []
vol.append(volume*)
采纳答案by Jon-Eric
You can use extendto append any iterable to a list:
您可以使用extend将任何可迭代对象附加到列表中:
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'))
回答by georg
Although you can do
虽然你可以做到
vol = []
vol += [val for name, val in globals().items() if name.startswith('volume')]
# replace globals() with locals() if this is in a function
a much better approach would be to use a dictionary instead of similarly-named variables:
更好的方法是使用字典而不是类似命名的变量:
volume = {
'A': 100,
'B': 20,
'C': 10
}
vol = []
vol += volume.values()
Note that in the latter case the order of items is unspecified, that is you can get [100,10,20]or [10,20,100]. To add items in an order of keys, use:
请注意,在后一种情况下,项目的顺序未指定,即您可以获得[100,10,20]或[10,20,100]。要按键的顺序添加项目,请使用:
vol += [volume[key] for key in sorted(volume)]
回答by sotapme
EDITremoved filterfrom list comprehension as it was highlighted that it was an appalling idea.
EDITfilter从列表理解中删除,因为它强调这是一个令人震惊的想法。
I've changed it so it's not too similar too all the other answers.
我已经改变了它,所以它与所有其他答案都不太相似。
volumeA = 100
volumeB = 20
volumeC = 10
lst = map(lambda x : x[1], filter(lambda x : x[0].startswith('volume'), globals().items()))
print lst
Output
输出
[100, 10, 20]
回答by user2040608
do you want to add the variables' names as well as their values?
您想添加变量的名称及其值吗?
output=[]
output.append([(k,v) for k,v in globals().items() if k.startswith('volume')])
or just the values:
或只是值:
output.append([v for k,v in globals().items() if k.startswith('volume')])

