蟒蛇; for loop;迭代现有的变量集

时间:2013-11-16 21:49:07

标签: python variables for-loop iteration pythonanywhere

假设我有一组已经创建的变量。它们使用类似的(即可预测的命名约定)。例如:

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

我的目标是能够迭代这些变量并检查它们是否包含“X”。这些变量由另一个for循环“自动生成”。

以下是我正在尝试的代码的较长示例:

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

因此,您可以看到我通过$枚举$迭代生成变量。我似乎无法找到一种方法来检查这些自动生成的变量(即job0,job1,job2,job3等)是否包含“X”或空格“”。这是我的尝试:

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

2 个答案:

答案 0 :(得分:1)

您已有一个列表:job_count_array。你现在所要​​做的就是循环遍历该列表:

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

这使您可以通过exec调用来放弃循环。看看有多容易?只需Keep data out of your variable names

每当您发现要生成动态变量时,生成一个列表或字典,它们更容易处理。

答案 1 :(得分:0)

你应该遵循Martijn Pieters的建议。

那就是说,我会回答你原来的问题。

变量存储在名为 globals 的字典中。你可以遍历那些并打印匹配:

 for varname, value in globals().values():
     if varname.startswith('job') and value == 'X':
         ...