如何通过遍历整数和字符串的组合来创建变量? [英] How can I create variables by iterating through a combination of integers and strings?

查看:73
本文介绍了如何通过遍历整数和字符串的组合来创建变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想通过遍历某种名称分配语句或函数来创建变量.我想结束使用标题为"t1t2t3"等的变量.如何完成

So I want to create variables by looping through some sort of name assigning statement or function. I want to end up having variables titled "t1, t2, t3" etc. How can I accomplish what

i = 1
while 1:
    ("t" + str(i)) = [0,0,0,0]
    i = i + 1

看起来会那样. (请保持str("t")在前面,而不是使第二个字符更改为int(i).这是为了创建变量,以便稍后将其放入数组中,而不必在代码中键入它们.)我正在尝试制作一个10,000个列表,每个列表包含4个元素.这更清楚吗?

looks like it would do. (Keep the str("t") at the front than make the second character the changing int(i). This is to create variables to later put in an array without having to type them out in the the code.) I'm trying to make a list of 10,000 lists with 4 elements each. Is this more clear?

推荐答案

虽然从技术上讲可以做您想做的事情,但这是一种非常糟糕的做法.这正是列表(或数组)用于的用例,您应该在此处使用一个用例.

While it is technically possible to do what you want, it's a really bad practice. This is exactly the use case that lists (or arrays) were made for, and you should be using one here.

根据您的代码示例,类似

Based on your code sample, something like

t = [[0] * 4 for i in xrange(10000)]

(正如David Alber在评论中提到的)应该为您工作;它将创建一个包含4个元素的10000个列表的列表.

(as David Alber mentioned in a comment) should work for you; it will create a list of 10000 lists of 4 elements each.

P.S.在Python 3中,xrange函数已重命名为range.

P.S. In Python 3, the xrange function has been renamed to range.

这篇关于如何通过遍历整数和字符串的组合来创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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