Give Name to List Variable

Give name to list variable

Since @akrun doesn't need any more points, here is an example showing how you can assign names to a list:

lst <- list(a="one", b="two", c=c(1:3))
names(lst)
[1] "a" "b" "c"
names(lst) <- c("x", "y", "z")

> lst
$x
[1] "one"

$y
[1] "two"

$z
[1] 1 2 3

How do I write the name of a variable in a list in c#?

Oakley is right. But I love dictionary in that case, because it's pretty simple and good in performance. Just check out the code.

Dictionary<string, int> dictionary = new Dictionary<string, int>();

dictionary.Add("var1", 4);
dictionary.Add("var2", 6);
dictionary.Add("var3", 12);

foreach (var i in dictionary)
{
System.Console.WriteLine(i.Key);
}

If you want that Key and Value could be any data type. Then you can use the following.

Dictionary<object, object> dictionary = new Dictionary<object, object>();

Python: how to assign a name of a list variable to a class

The usual way we define classes is with the class keyword, naturally.

class B(A):
some_variable = 100

Effectively, we're constructing a new type in the Python runtime. And, in fact, types have their own constructor in Python; it's called type and we can call it directly. The above declaration is roughly equivalent to

B = type('B', ('A',), { 'some_variable': 100 })

And now the type names are strings. There's just one more piece of the puzzle we'll need. We want to take and assign it to the name B, using a string so we can do so with names that aren't known in advance. Assuming you want to do this at module-scope, we can use globals, which returns a dictionary of the current module's top-level variables, which we can freely modify to add more variables. So we can do

globals()['B'] = type('B', ('A',), { 'some_variable': 100 })

Now, let's put those pieces together and write a script that uses the lst list you suggested.

lst = [['B', 'A'], ['C', 'B'], ['D', 'B'], ['E','C D']]

# Iterate over the list.
for class_name, superclass_names in lst:
# Here, we're going to lookup all of the superclass names in the
# current global scope. It's a little more complicated than that,
# since we also want to *create* any names that don't exist (like
# 'A' in your example) when we find them.
superclasses = []
for superclass_name in superclass_names.split(' '):
# If the name doesn't exist, create it and assume its
# supertype is object, the root of Python's type hierarchy.
if superclass_name not in globals():
globals()[superclass_name] = type(superclass_name, (object,), {})
# Get the class, whether it's the one we just made or one that
# already exists.
superclasses.append(globals()[superclass_name])
# Now we construct the new class. The first argument to type() is
# the class name, the second is all of the superclasses (it must
# be a tuple, not a list, according to the documentation, so we
# convert it), and finally the contents. Since you just want the
# classes themselves, I'll assume the contents are meant to be
# empty. You can easily change that as needed.
globals()[class_name] = type(class_name, tuple(superclasses), {})

# Now let's see that everything is defined correctly. __mro__ is a
# complicated concept, but the basic idea is that it should give us E,
# followed by all of its subclasses in a reasonable order (for some
# definition of reasonable).
print(E.__mro__)

Try it online!

Name list elements based on variable names R

You cannot assign to paste() using the <- operator (and I believe this is true for the eval() function as well). Instead, you need to either use the [[ operator or use the names() function. You can do this like so:

L <- list()
var1 <- "wood"
var2 <- 1.0
var3 <- "z4"
varname <- paste(var1, as.character(var2), var3, sep="_")

# Using [[
L[[varname]] <- c(0,1)

> L
$wood_1_z4
[1] 0 1

# Using names()
L[[1]] <- c(0,1)
names(L)[1] <- varname

> L
$wood_1_z4
[1] 0 1

A more effective way to do this might be to use a function that both creates the value and names the list element, or even one that just creates the value - if you then use sapply you can name each list element using arguments from the call to your function and the USE.NAMES options.

In a general sense, R isn't really well-optimized for growing lists over time when the final size and structure of the list aren't well-known. While it can be done, a more "R-ish" way to do it would be to figure out the structure ahead of time.

How to change and assign the name of a list?

You’d use (nested) lists for this purpose. At its most rudimentary, this could look as follows:

results = list()

for (var in c('foo', 'bar', 'baz')) {
results[[var]] = list1
}

This will generate a new list with three items named foo, bar and baz, each of which is a copy of list1. To access the individual values, you’d use e.g. result$foo, or result[['foo']] (the latter is necessary if you have the value’s name stored in a variable, since access via $ doesn’t work with variables on the right-hand side).

You can adapt this for your specific purposes. Do note that, in most cases, the loop would be replaced by a more appropriate function. For instance, the above would be done better using replicate:

result = setNames(replicate(3L, list1, simplify = FALSE), c('foo', 'bar', 'baz'))

Either way, don’t dynamically create variables. It’s never an appropriate solution for this kind of problem. Instead, it makes the code more complex and harder to understand. To keep code as simple as possible, variables should only be created explicitly in code (i.e. by assignments or as function parameters, etc.).

Create List with name from variable

Sounds like you want a Dictionary of List<string>s:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

foreach (var line in myList)
{
dict.Add(line, new List<string>());
}

Now you can access each list based on the original string we used for the key:

List<string> aList = dict["a"];

Python List as variable name

This is a bad idea. You should not dynamically create variable names, use a dictionary instead:

variables = {}
for name, colour, shape in Applist:
variables[name + "_n"] = name
variables[name + "_c"] = colour
variables[name + "_s"] = shape

Now access them as variables["Apple_n"], etc.

What you really want though, is perhaps a dict of dicts:

variables = {}
for name, colour, shape in Applist:
variables[name] = {"name": name, "colour": colour, "shape": shape}

print "Apple shape: " + variables["Apple"]["shape"]

Or, perhaps even better, a namedtuple:

from collections import namedtuple

variables = {}
Fruit = namedtuple("Fruit", ["name", "colour", "shape"])
for args in Applist:
fruit = Fruit(*args)
variables[fruit.name] = fruit

print "Apple shape: " + variables["Apple"].shape

You can't change the variables of each Fruit if you use a namedtuple though (i.e. no setting variables["Apple"].colour to "green"), so it is perhaps not a good solution, depending on the intended usage. If you like the namedtuple solution but want to change the variables, you can make it a full-blown Fruit class instead, which can be used as a drop-in replacement for the namedtuple Fruit in the above code.

class Fruit(object):
def __init__(self, name, colour, shape):
self.name = name
self.colour = colour
self.shape = shape

How can I name a list variable with its first element?

Do you really have to do it this way and saving every list individually in a new variable?

In my opinion a better option would be to use a 2-dimensional List and accessing your elements via their indices, e.g. lines[0][1]. This would be a "list of lists", where the outer list contains your lines, each line in the format of another list.

You can read more about lists of lists here.

Use strings in a list as variable names in Python

This code can help you:

user_contract = ['ZNZ6','TNZ6','ZBZ6']
data = [[1,2,3],[4,5,6],[7,8,9]]
dictionary = dict(zip(user_contract, data))
print(dictionary)

It creates a dictionary from the two lists and prints it:

python3 pyprog.py 
{'ZBZ6': [7, 8, 9], 'ZNZ6': [1, 2, 3], 'TNZ6': [4, 5, 6]}


Related Topics



Leave a reply



Submit