Assign The Result Of A Loop To A Variable In Python
Consider a list I want to parse using a for : friends = ['Joe', 'Zoe', 'Brad', 'Angelina', 'Zuki', 'Thandi', 'Paris'] for i in friends: print i will return : 'Joe', 'Zoe', 'Bra
Solution 1:
If I understand well, you'd like to dynamically create variables. Here it is.
from collections import OrderedDict
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
d = OrderedDict()
for idx, value inenumerate(friends):
key = 'var' + str(idx)
d[key] = value
print(d)
# Output
OrderedDict([('var0', 'Joe'), ('var1', 'Zoe'), ('var2', 'Brad'), ('var3', 'Angelina'), ('var4', 'Zuki'), ('var5', 'Thandi'), ('var6', 'Paris')])
Solution 2:
I also have this question, this is how I managed to solve it somewhat:
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
new_friends = ' '.join([x for x in friends])
print(new_friends)
Will return:
Joe Zoe Brad Angelina Zuki Thandi Paris
Solution 3:
var = ''
friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
for i in friends:
var=i
if list and loop are in function then declare var as global
globalvar
in starting of function
Solution 4:
If you want to join the values in friends
into a comma-separated string, that would be
s = ','.join(friends)
If you want to include quotes around the names, maybe something like
s = ','.join(['"{0}"'.format(x) for x in friends])
Solution 5:
Try this at the end of the loop:
the_variable = the_variable + i
However, if you are to do this, you should add a space to the end of every item in the dictionary, otherwise it will output:
JoeZoeBradAngelinaZukiThandiParis
Post a Comment for "Assign The Result Of A Loop To A Variable In Python"