Assign the result of a loop to a variable in Python

前端 未结 6 1803
予麋鹿
予麋鹿 2021-01-20 11:48

Consider a list I want to parse using a for :

friends = [\"Joe\", \"Zoe\", \"Brad\", \"Angelina\", \"Zuki\", \"Thandi\", \"Paris\"]
for i in fri         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 11:53

    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 in enumerate(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')])
    

提交回复
热议问题