深度阅读

How to dynamically create variables in a loop in Python

作者
作者
2023年08月22日
更新时间
5.72 分钟
阅读时间
0
阅读量

To dynamically create variables in a loop in Python, you can use a dictionary (or another data structure) to store and access the values. For example:

values = [1, 2, 3, 4, 5]
my_dict = {}
for i in range(len(values)):
    my_dict[f"var_{i}"] = values[i]

# Access the values using the dictionary key
print(my_dict["var_0"]) # Output: 1
print(my_dict["var_1"]) # Output: 2

In this example, instead of trying to access non-existent dynamically created variable names, we use the dictionary key (“var_0”, “var_1”, etc.) to access the values in the dictionary.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。