Question

I have a key two sets of identical int variables from two different objects, but one starts its the first element of with 0 and the other with 1

a = 0, b = 5, c = 7 # var_abc
x = 1, y = 6, d = 6 # var_xyz

In order to do other processes, i must convert var_xyz such that var_xyz == var_abc, so i have to do code this line for each variable in var_xyz:

x,y,z = x-1, y-1, z-1

If we are simply instantiating the variables in var_xyz, we could have done this:

x,y,z = (0,)*3

Is there are another way such that i don't need to hardcode var-1 for each variable in var_xyz? Imagine if there are like 1000 variables in var_xyz.

Was it helpful?

Solution

You've noticed that the duplication for the case of one thousand variables would be a nuisance, which is good. That suggests that you need to move up one level of abstraction, so that instead of one thousand variables you'd have one list or one dictionary, which can then be looped over.

For example, if it makes sense to count your variables starting from 0, you could use a list:

>>> vv = [10,20,30,40,50]
>>> vv[3]
40

and then use a list comprehension to do the subtraction:

>>> vv = [v-1 for v in vv]
>>> vv
[9, 19, 29, 39, 49]
>>> vv[3]
39

or if it was important that the variables had names, you could use a dictionary:

>>> # first, let's make a test dictionary
>>> from string import ascii_lowercase
>>> d = {k: i for i, k in enumerate(ascii_lowercase[:10])}
>>> d
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'j': 9}
>>> d['d']
3

and use a dictionary comprehension to simplify the subtraction:

>>> d = {k: v-1 for k,v in d.iteritems()}
>>> d['d']
2

OTHER TIPS

You can do:

x,y,z = [v - 1 for v in (x,y,z)]

However it doesn't help a possible 1000 variable scenario. It's unclear what would you want to do then, other than having a list or dict instead of separate variables.

If I understand you correctly, you could use list comprehension:

orig_list = [x,y,z]
minus_list = [value - 1 for value in orig_list]
# if desired put a,b,c up there or...
a,b,c = minus_list

Use a list or dict. That's it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top