你如何(解决)动态变量命名? [英] How do you (get around) dynamically naming variables?

查看:166
本文介绍了你如何(解决)动态变量命名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如果我使用的是正确命名,所以我会尽量让我的问题越具体越好。这就是说,我想这个问题出现的时候,而且有可能是几种不同的方法来处理它。

I'm not sure if I'm using the right nomenclature, so I'll try to make my question as specific as possible. That said, I imagine this problem comes up all the time, and there are probably several different ways to deal with it.

比方说,我有一个名为阵列(矢量) 1980年和2000年之间,我想使20个单独的阵列(矢量)出来的1000个随机年。这些阵列将被命名为 array1980 array1981 等,也将有1000的长度,但会包含1S,其中指数在名称在和0别处等于相应的元素。换句话说:

Let's say I have an array (vector) called main of 1000 random years between 1980 and 2000 and that I want to make 20 separate arrays (vectors) out of it. These arrays would be named array1980, array1981, etc., would also have length 1000 but would contain 1s where the index in the name was equal to the corresponding element in main and 0s elsewhere. In other words:

for(int i=0; i<1000; i++){
    if(main[i]==1980){
       array1980[i]=1;
    } else {
       array1980[i]=0;
    }

当然,我不希望有写的这二十,所以它会是很好的,如果我可以创建一个循环内的新变量名。问题是,你不能笼统地分配变量名称与运营商,例如前pressions。

Of course, I don't want to have to write twenty of these, so it'd be good if I could create new variable names inside a loop. The problem is that you can't generally assign variable names to expressions with operators, e.g.,

String("array"+ j)=... # returns an error

我目前使用Matlab的最多的,但我也可以做一个小的JAVA,C ++和Python,我试图让人们如何去一般的解决这个问题的想法。理想情况下,我想能够操纵以某种方式单个变量(或子阵列),今年仍然在变量名(或数组索引),以减少错误的机会,并让事情更容易处理一般来说。

I'm currently using Matlab the most, but I can also do a little in Java, c++ and python, and I'm trying to get an idea for how people go about solving this problem in general. Ideally, I'd like to be able to manipulate the individual variables (or sub-arrays) in some way that the year remains in the variable name (or array index) to reduce the chance for error and to make things easier to deal with in general.

我倒是AP preciate任何帮助。

I'd appreciate any help.

推荐答案

解决这个问题的一般解决方法是不能创建动态变量名,而是改为建立一个映射。这正是如何完成由语言而异。

The general solution to this is to not create variables with dynamic names, but to instead create a map. Exactly how that's done will vary by language.

有关Java的,这是值得看的太阳藏品的地图部分教程的一个开始。

For Java, it's worth looking at the map section of the Sun collections tutorial for a start.

这篇关于你如何(解决)动态变量命名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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