简体   繁体   中英

Append several variables to a list in Python

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.

volumeA = 100
volumeB = 20
volumeC = 10

vol = []

vol.append(volume*)

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'))

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:

vol += [volume[key] for key in sorted(volume)]

EDIT removed filter from list comprehension as it was highlighted that it was an appalling idea.

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]

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')])

if I get the question appropriately, you are trying to append different values in different variables into a list. Let's see the example below. Assuming :

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

Hope this helps, thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM