如果您只想匹配值,则可以使用列表:
>>> pcode1 = 239
>>> pcode2 = 245
>>> pcode3 = 210
>>> pcode4 = 217
>>> lis = [pcode1, pcode2, pcode3, pcode4]
>>> allpcode= 220
>>> for i,x in enumerate(lis):
if x < allpcode:
print "pcode{} is less than {}".format(i+1,allpcode)
elif x > allpcode:
print "pcode{} is greater than {}".format(i+1,allpcode)
...
pcode1 is greater than 220
pcode2 is greater than 220
pcode3 is less than 220
pcode4 is less than 220
更好地使用字典:
由于变量只是对 python 中值的引用,因此您无法访问变量名。如果你有很多pcodes
然后为它们中的每一个定义一个变量是解决这个问题的坏方法,那么使用 dict 会更干净。
#create dictionary with keys named pcode1, pcode2,...
>>> dic = {'pcode1':239, 'pcode2':245, 'pcode3':210, 'pcode4':217}
>>> for k,v in dic.items():
if v < allpcode:
print "{} is less than {}".format(k ,'allpcode')
elif v > allpcode:
print "{} is greater than {}".format(k,'allpcode')
...
pcode3 is less than allpcode
pcode2 is greater than allpcode
pcode1 is greater than allpcode
pcode4 is less than allpcode
尽管字典不维护任何顺序,但您可能必须collections.OrderedDict
或sorted
在这里以特定顺序获取键。