Python: using a loop to do the same with several variables - python

I have 30 variables with the pattern aod7039, aod7040, ...., aod7068.
I want to do the same operation (i.e. calculate the mean over an axis) for all these variables and overwrite the original variables.
Up to now I wrote 30 times the same line, and wondered if there isn't maybe an shorter and easier way to do this?
I am gradeful for every idea!

Firstly, don't use 30 variables, use a list aod[]
Secondly, use
for i in range(7039, 7069):
aod[i] = yourFunction(aod[i])
to override existing list

This will get you all values of variables that start with 'aod'
values = [v for k,v in globals() if k.startswith('aod')]
But having 30 variables smells bad.

If I understand your question right, you just want to iterate over those variables?
If so you could keep references on some list/dictionary and then iterate/update this way.
List = []
List.append(aod7039)
for item in List:
#do something

I have 30 variables with the pattern aod7039, aod7040, ...., aod7068
Then you have a design problem - you should have a list or dict instead. Replace all those variables with either a list or dict (or collections.OrderedDict if you need key access while preserving insertion order) and then it's only a matter of iterating over your container, ie
# with a list:
for index, item in enumerate(yourlist):
yourlist[index] = do_something_with(item)
# with a dict or OrderedDict:
for key, item in enumerate(yourdict):
yourdic[key] = do_something_with(item)

store your 30 variables in a list and use map to tackle it without any loop:
varlist=[aod7039, aod7040, ...., aod7068]
result=list(map(yourfunction, varlist))

Related

Using locals() to create a list of dictionaries

This might be simple, but I'm stuck. I have globals() that creates dictionaries based on zipping lists (that will differ in sizes, thus differ in the number of the dictionaries that get created). The new dictionaries that get created look like the below:
dict0 = {foo:bar}
dict1 = {more_foo:more_bar}
How do I call these new dictionaries in a for loop?
I want my script to do the below:
for i in (dict0, dict1):
The only issue is that the number of dictx (dictionaries) will differ based on the inputs from the script.
As nicely put in comments, in your case, you should append the dictionaries to a list:
list_iterator = list()
# create dict 1.
list_iterator.append(dict1)
# create dict 2.
list_iterator.append(dict2)
# and so on. If your dict create algorithm is repetetive, you can add the append command to the end.
I figured it out...
for i in range(len(someList)):
dicts = locals()['dict' + str(i)]

Assign list values to dictionary keys

So I want to loop over a dictionary and a list simultaneously without them being nested.
What I really mean is:
for i,c in enumerate(dictionary) and for k in range(len(list)):
dictionary[c] = list[k]
So it basically loops over one dictionary and I can assign values to the dictionary with a list.
IIUC, you are trying to reassign existing keys to list values. This is something you can only do from python-3.7 onwards (or 3.6 if you use CPython). This can be done either through direct reassignment,
dictionary = dict(zip(dictionary, lst))
Or, if they are not the same length, and there are keys you want to preserve, use dict.update:
dictionary.update(dict(zip(dictionary, lst)))
Additionally, it is unwise to name variables after builtin objects (such as list).
zip is your friend
dictionary.update(zip(dictionary, lst))

Initialize a list using inline for loop

I am initializing my list object using following code.
list = [
func1(centroids[0],value),
func1(centroids[1],value),
....,
func1(centroids[n],value)]
I am trying to do it a more elegant way using some inline iteration. Following is the pseudo code of one possible way.
list = [value for value in func1(centroids[n],value)]
I am not clear how to call func1 in an iterative way. Can you suggest a possible implementation?
For a list of objects, Python knows how to iterate over it directly so you can eliminate the index shown in most of the other answers,
res = [func1(c, value) for c in centroids]
That's all there is to it.
A simple list comprehension consists of the "template" list element, followed by the iterator needed to step through the desired values.
my_list = [func1(centroids[0],value)
for n in range(n+1)]
Use this code:
list = [func1(centroids[x], value) for x in range(n)]
This is called a list comprehension. Put the values that you want the list to contain up front, then followed by the for loop. You can use the iterating variable of the for loop with the value. In this code, you set up n number(s) of variable(s) from the function call func1(centroids[x], value). If the variable n equals to, let's say, 4, list = [func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value)] would be equal to the code above

Python - How to turn an integer into a list inside of a dictionary

I have a dict containing 2 key-value pairs, one is a list
dict_special =
{'money' : 100,
'sweets' : ['bonbons','sherbet', 'toffee','pineapple cube']}
I would like to turn the first value into a list also, so I can append items
i.e.
dict_special =
{'money' : [100, 250, 400]
'sweets' : ['bonbons','sherbet', 'toffee','pineapple cube']}
This is what I have tried so far:
newlist = [dict_special['money']]
newlist.append(250)
dict_special['money'] = newlist
But I feel that there must be a more succinct and Pythonic way to get there.
Any suggestions?
A more concise way to write this:
newlist = [dict_special['money']]
newlist.append(250)
dict_special['money'] = newlist
… would be:
dict_special['money'] = [dict_special['money'], 250]
However, it's worth looking at why you're trying to do this. How did you create the dict in the first place? Maybe you should have been creating it with [100] in the first place, instead of 100. If not, maybe you should have another step for converting the input dictionary (with 100) into the one you want to use (with [100]) generically rather than doing it on the fly here. Maybe you even want to use a "multidict" class instead of using a dict directly.
Without knowing more about your code and your problem, it's hard to say, but trying to make these kinds of changes in an ad-hoc way is usually a sign that something is wrong somewhere else in the code.
How about:
newList = {key: value if isinstance(value, list) else [value]
for key, value in dict_special.items()}

in a loop, only add to a dictionary or list or tuple if doesn't contains the key

I am looping in python and want to add a key to a dictionary only if it isn't already in the collection.
How can I do this?
mydic = {}
for x in range(100):
??
For a dict, it's easy and fast:
for x in range(100):
if x not in mydic:
mydic[x] = x # or whatever value you want
that is, just check with not in instead of in.
This is great for a dict. For a list, it's going to be extremely slow (quadratic); for speed, you need to add an auxiliary set (hopefully all items in the list are hashable) before the loop, and check and update it in the loop. I.e.:
auxset = set(mylist)
for x in range(100):
if x not in auxset:
auxset.add(x)
mylist.append(x) # or whatever
For a tuple, it's impossible to add anything to it, or in any other way modify it, of course: tuples are immutable! Surely you know that?! So, why ask?

Categories

Resources