How to Assign Values to Dynamic Names Variables

how to create variable names dynamically and assigning values in python?

As noted in RunOrVeith's answer, a Dict is probably the right way to do this in Python. In addition to eval, other (non-recommended) ways to do this including using exec or setting local variables as noted here

stri = "mat"

for i in range(1,3):
exec("_".join([stri, str(i)])+'=1')

or locals,

stri = "mat"

for i in range(1,3):
locals()["_".join([stri, str(i)])] = 1

This define mat_1 = 1 and mat_2 = 1 as required. Note a few changes to your example (str(i) and range(1,3) needed, for python3 at least).

How to assign values to dynamic names variables

use assign as in:

x <- 1:10

for(i in seq_along(x)){
assign(paste('X', i, sep=''), x[i])
}

Assigning variables with dynamic names in Java

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.


1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

Dynamically assigning variable names JavaScript

Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:

  1. Specify them the fixed way (e.g. obj.propertyName = 'Value')
  2. Specify them using array notation (e.g. obj[propertyName] = 'Value'). In this case, note that propertyName is a string value.

In both cases, the result will be exactly the same. You could retrieve those properties likewise, e.g. obj.propertyName and obj[propertyName]. Both will return 'Value'.

In your case, @LuudJacobs's suggestion about using the window object will most probably do the trick...

Dynamic variable name php 7.4 and value assigment

This piece of code will work in the newest version of PHP as well.

$column = 'A';

${"total{$column}"} = 20;

echo ${"total{$column}"}; // 20

echo $totalA; // 20

Use dynamic variable names in JavaScript

Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).

So if you create variables like this:

var a = 1,
b = 2,
c = 3;

In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).

Those can get accessed by using the "dot" or "bracket" notation:

var name = window.a;

or

var name = window['a'];

This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:

function foobar() {
this.a = 1;
this.b = 2;

var name = window['a']; // === undefined
console.log(name);
name = this['a']; // === 1
console.log(name);
}

new foobar();

R: Read dynamic variable names generated in for loop

You may use get to do this -

library(dplyr)

for (i in 1:nrow(LabviewFiles)){
assign(x = paste("P",i , "Onsets_PRH", sep = "_"), value = t(subset.data.frame(All_Phase, All_Phase$Phase==i) %>%
filter(CONDITIONS == "NULL_TRIAL",
MISC_REWARD == 1,
MISC_PASSIVE_FAILED == 1) %>%
select(Feedback_onset)))

assign(x = paste("P",i , "Durations_PRH", sep = "_"), value = t(rep(0.5, times = length(get(paste("P",i , "Onsets_PRH", sep = "_"))))))
}

Note that using assign and creating variables in global environment is discouraged. You may also read Why is using assign bad?

How to create a dynamic variable and assign value to it?

You can use bash's declare directive and indirection feature like this:

p_val="foo"
active_id=$p_val
declare "flag_$active_id"="100"

TESTING:

> set | grep flag
flag_foo=100

UPDATE:

p_val="foo"
active_id="$p_val"
v="flag_$active_id"
declare "$v"="100"

> echo "$v"
flag_foo
> echo "${!v}"
100

Usage in if condition:

if [ "${!v}" -ne 100 ]; then
echo "yes"
else
echo "no"
fi

# prints no


Related Topics



Leave a reply



Submit