0

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

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
4

2 回答 2

1

您已经有一个列表:job_count_array。您现在要做的就是遍历该列表:

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

exec这也让您可以通过调用放弃循环。看看这有多容易?只需将数据保留在变量名称之外

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

于 2013-11-16T21:53:55.630 回答
0

你应该听从 Martijn Pieters 的建议。

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

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

 for varname, value in globals().values():
     if varname.startswith('job') and value == 'X':
         ...
于 2013-11-16T22:01:51.823 回答