我想将几个变量附加到列表中,变量的数量是不确定的。所有变量都以"volume"开头。我在想也许通配符或者类似的东西可以做到这一点。但我找不到类似的东西。有什么想法解决这个问题吗?请注意,在这个例子中有三个变量,但它也可能是五个、六个或任何数量。
volumeA = 100
volumeB = 20
volumeC = 10
vol = []
vol.append(volume*)
我想将几个变量附加到列表中,变量的数量是不确定的。所有变量都以"volume"开头。我在想也许通配符或者类似的东西可以做到这一点。但我找不到类似的东西。有什么想法解决这个问题吗?请注意,在这个例子中有三个变量,但它也可能是五个、六个或任何数量。
volumeA = 100
volumeB = 20
volumeC = 10
vol = []
vol.append(volume*)
您可以使用 extend
将任何可迭代对象附加到列表中:
vol.extend((volumeA, volumeB, volumeC))
根据变量名称的前缀来做事情会让我感到代码有异味,但你可以这样做。(添加值的顺序是未定义的。)
vol.extend(value for name, value in locals().items() if name.startswith('volume'))
如果顺序很重要(在我看来,仍然有点不太对):
vol.extend(value for name, value in sorted(locals().items(), key=lambda item: item[0]) if name.startswith('volume'))
TypeError: 'int' object is not iterable
。 - Boruto Uzumakivol = []
vol += [val for name, val in globals().items() if name.startswith('volume')]
# replace globals() with locals() if this is in a function
一个更好的方法是使用字典代替同名变量:
volume = {
'A': 100,
'B': 20,
'C': 10
}
vol = []
vol += volume.values()
[100,10,20]
或[10,20,100]
。要按键的顺序添加项目,请使用:vol += [volume[key] for key in sorted(volume)]
编辑从列表推导式中移除了filter
,因为这是一个令人震惊的想法。
我已经做出了更改,使其与所有其他答案不太相似。
volumeA = 100
volumeB = 20
volumeC = 10
lst = map(lambda x : x[1], filter(lambda x : x[0].startswith('volume'), globals().items()))
print lst
[100, 10, 20]
map
只是为了继续使用filter
,这样做甚至更加丑陋。我认为JBernardo的观点是,推导式已经内置了可选的if子句,因此应该使用它来代替filter
。 - Jon-Eric您是否想添加变量名称以及它们的值?
output=[]
output.append([(k,v) for k,v in globals().items() if k.startswith('volume')])
output.append([v for k,v in globals().items() if k.startswith('volume')])
email = 'example@gmail.com'
pwd='Mypwd'
list = []
list.append(email)
list.append (pwd)
for row in list:
print(row)
# the output is :
#example@gmail.com
#Mypwd