Skip to main content
 首页 » 编程设计

python之自动更新变量

2025年05月04日13bjzhanghao

我有一个包含一个或多个项目的列表:

fruits = ['apple', 'orange', 'pear'] #or could be one or many 

我想根据项目的数量创建变量: 代码:

    for i in range(len(fruits)): 
        "Fruit".format(i) = fruits[i] 

我想获取:

    Fruit1=apple, Fruit2=orange, Fruit3=pear 

对我如何得到这个有什么帮助吗?

请您参考如下方法:

作为此类任务的正确方法,您可以使用字典:

>>> fruits = ['apple', 'orange', 'pear'] 
>>> d={"Fruit{}".format(i):j for i,j in enumerate(fruits,1)} 
>>> d 
{'Fruit1': 'apple', 'Fruit2': 'orange', 'Fruit3': 'pear'} 
>>> d['Fruit1'] 
'apple' 

请注意,如果您使用像字典这样的数据结构来解决您的问题,您将获得很多优势,例如,您可以使用 dict.values() 访问所有值 和所有带有 dict.keys() 的键也可以更容易地与其他数据结构交互!

>>> d.keys() 
['Fruit1', 'Fruit2', 'Fruit3'] 
>>> d.values() 
['apple', 'orange', 'pear']