You probably want a dict instead of separate variables. For example
d = {}
for i in range(3):
d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals function:
for i in range(3):
locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr function
for i in group(3):
setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
Answer from Eli Courtwright on Stack OverflowYou probably want a dict instead of separate variables. For example
d = {}
for i in range(3):
d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals function:
for i in range(3):
locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr function
for i in group(3):
setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
Use a list.
groups = [0]*3
for i in xrange(3):
groups[i] = self.getGroup(selected, header + i)
or more "Pythonically":
groups = [self.getGroup(selected, header + i) for i in xrange(3)]
For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:
l = locals()
for i in xrange(3):
l['group' + str(i)] = self.getGroup(selected, header + i)
but that's really bad form, and possibly not even guaranteed to work.
Changing variable name in for loop?
Changing a variable name in a for loop?
"I want to define several variables with trailing ascending numbers 0, 1, 2, etc." is a red flag that you really should be using a list.
More on reddit.compython - How to have a variable that changes its name after every loop? - Stack Overflow
python - How do you create different variable names while in a loop? - Stack Overflow
You can access the globals() dictionary to introduce new variables. Like:
for i in range(0,5):
globals()['x'+str(i)] = i
After this loop you get
>>> x0, x1, x2, x3, x4
(0, 1, 2, 3, 4)
Note, that according to the documentation, you should not use the locals() dictionary, as changes to this one may not affect the values used by the interpreter.
Using a dict:
arraysDict = {}
for i in range(0,3):
arraysDict['x{0}'.format(i)] = [1,2,3]
print arraysDict
# {'x2': [1, 2, 3], 'x0': [1, 2, 3], 'x1': [1, 2, 3]}
print arraysDict['x1']
# [1,2,3]
Using a list:
arraysList = []
for i in range(0,3):
arraysList.append([1,2,3])
print arraysList
# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
print arraysList[1]
# [1, 2, 3]
Hello,
I know this is probably a really basic python task, but I have been unable to figure it out. I am using python-pptx to create a powerpoint. My actual script is more complex, but for the sake of this question, suppose I have a for loop with which I iterate on a list, and create a new slide for each item in the list. The python-pptx library requires that I name each new slide something different - how do I update the name of the variable for each loop iteration? In the example below, how would "slide1" become "slide2" as the loop progresses through the list?
list_of_slide_content = ["example","of","content"]
for cont in list_of_slide_content:
slide1 = pptx.slide(0)
slide1.add_text(cont)I wasn't really sure how to describe this, but bascially this is what I want to do:
a1=1;a2=2;a3=3
for i in [1,2,3]: print a(i)
I want this to print a1, a2, and a3. Is there a way to make that work?
"I want to define several variables with trailing ascending numbers 0, 1, 2, etc." is a red flag that you really should be using a list.
You probably want to defer to r/learnpython for these types of questions.
Nevertheless, it's not clear what you want to do. On the one hand, you could just make a a list and index into that:
a = [1, 2, 3]
for i in [0, 1, 2]:
print(a[i])
Or, probably what you want to do is put these things in a dictionary:
data = {'a1': 1, 'a2': 2, 'a3': 3}
for i in [1, 2, 3]:
print(data['a{}'.format(i)])
Sure you can; it's called a dictionary:
d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
It is really bad idea, but...
for x in range(0, 9):
globals()['string%s' % x] = 'Hello'
and then for example:
print(string3)
will give you:
Hello
However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.
I have a large data frame I am creating smaller data frames with. Basically, there is one giant data frame with different departments information, so, I am creating smaller data frames, all the rows labeled purchasing will go into a smaller data frame, engineering, accounting, etc.
I created a while loop to go through the length of the large data frame and want to assign each smaller data frame with it's own name. Code might explain it better. It is below.
n=0
while n < len(df_dept_list.index):
dept = df_dept_list.iloc[n]
df_dept = df_all_data [
(df_all_data['Department'] == dept)].dropna()
n = n + 1I would like to just have the data frame name change each iteration like df_dept0, then df_dept1, something that changes with the value 'n'.
Any ideas how to?
You just need to fix the line arcpy.FeatureToPolygon_management(lyr, output + '\lyr', '#', 'ATTRIBUTES', '#'). Currently you have 'lyr' as a string. Here's an update that uses lyr as a variable for your output:
import arcpy
import os
arcpy.env.workspace = "C:\Users\Daimon Nurse\Desktop\Grounds Project"
mxd = arcpy.mapping.MapDocument(r"C:\Users\Daimon Nurse\Desktop\Grounds Project\ZonesMAP.mxd")
Layerlist = arcpy.mapping.ListLayers(mxd)
for lyr in arcpy.mapping.ListLayers(mxd):
output = r'C:\Users\Daimon Nurse\Desktop\Grounds Project\DFMGROUNDS.gdb'
outfile = os.path.join (output, lyr)
arcpy.FeatureToPolygon_management(lyr, outfile, '#', 'ATTRIBUTES', '#')
del mxd
Using the lyr variable, instead of defining the string, should work:
for lyr in arcpy.mapping.ListLayers(mxd):
output = r'C:\Users\Daimon Nurse\Desktop\Grounds Project\DFMGROUNDS.gdb'
arcpy.FeatureToPolygon_management(lyr, output + '\' + lyr, '#', 'ATTRIBUTES', '#')
del lyr
Use a dictionary instead. E.g:
doubles = dict()
for x in range(1, 13):
doubles[x] = x * 2
Or if you absolutely must do this AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING, you can assign to locals() as to a dictionary:
>>> for x in range(1, 13):
... locals()['double_{0}'.format(x)] = x * 2
...
>>> double_3
6
There never, ever should be a reason to do this, though - since you should be using the dictionary instead!
expanding my comment: "use a dict. it is exactly why they were created"
using defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(int)
using normal dict:
>>> d = {}
the rest:
>>> for x in range(1, 13):
d['double_%02d' % x] = x * 2
>>> for key, value in sorted(d.items()):
print key, value
double_01 2
double_02 4
double_03 6
double_04 8
double_05 10
double_06 12
double_07 14
double_08 16
double_09 18
double_10 20
double_11 22
double_12 24