如何在循环中创建不同的变量名称? [英] How do you create different variable names while in a loop?

查看:49
本文介绍了如何在循环中创建不同的变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如目的...

 for x in range(0,9):字符串'x' = "你好"

所以我最终得到 string1, string2, string3 ... 都等于 "Hello"

解决方案

当然可以;它被称为字典:

d = {}对于范围内的 x(1, 10):d["string{0}".format(x)] = "你好"

<预><代码>>>>d["string5"]'你好'>>>d{'string1': '你好','string2': '你好','string3': '你好','string4': '你好','string5': '你好','string6': '你好','string7': '你好','string8': '你好','string9': '你好'}

我说这话有点含糊其辞,但实际上将一个值与另一个值相关联的最佳方式是字典.这就是它的设计目的!

For example purposes...

for x in range(0,9):
    string'x' = "Hello"

So I end up with string1, string2, string3... all equaling "Hello"

解决方案

Sure you can; it's called a dictionary:

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"

>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!

这篇关于如何在循环中创建不同的变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆