문제

Suppose I have a set of variables which are already created. They use a similar (i.e. predictable naming convention). Example:

job0 = "X"
job1 = " "
job2 = " "
job3 = "X"
job4 = "X"

My aim is to be able to iterate over these variables and check whether or not they contain a "X". These variables are 'auto-generated' by another for loop.

Here is a longer example of the code I am experimenting with:

job_count_array = []
global job_count
for i in range(2, job_count+1):
    job_count_array.append("sel.get_text(//form[@id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small)" % i)
print job_count_array #output for debug purposes
for l, value in enumerate(job_count_array):
    exec "job%d = value" % l #auto-generates variables with the above list indices

So, as you can see I get the variables generated through $enumerate$ iteration. I can't seem to find a way to check whether or not these auto-generated variables (i.e. job0, job1, job2, job3, etc) contain either an "X" or a blank space " ". Here is my attempt:

for i in range(0, job_count-1):
    print "job%d" % i
    if "job%d" % i == "X":
        print "Excluding Job%d: Found Locked Status" % i
        #I plan to add code to this line that will allow me to exclude the job this variable refers to for further testing/evaluation
    if job%d % i == " ":
        print "Including Job%d: Found Unlocked Status" % i
        #I plan to add code to this line that will allow me to include the job this variable refers to for further testing/evaluation
도움이 되었습니까?

해결책

You already have a list: job_count_array. All you have to do now is loop over that list:

for job in job_count_array:
    if job == "X":
        # etc.

This lets you drop the loop with exec calls too. See how much easier that is? Just Keep data out of your variable names.

Whenever you find you want to generate dynamic variables, generate a list or dictionary instead, they are far easier to handle.

다른 팁

You should follow Martijn Pieters advice.

That said, I will answer your original question.

The variables are stored in a dictionary called globals. You can loop over those and print matches:

 for varname, value in globals().values():
     if varname.startswith('job') and value == 'X':
         ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top