【发布时间】:2014-10-06 04:00:09
【问题描述】:
我正在编写一个程序来分配客户许可证。但是,无论何时更改数据库中的许可证,都需要在另一个程序中进行更改。但是我遇到了麻烦,因为我在字典中嵌套了一个列表,当我在字典中使用 if id 时,即使我肯定知道它在那里也找不到它。
annotation = {'customer_id': 35, 'guest_os': 1287, 'license': [('VMware VM', 01), ('Veeam Backup VM', 02)]}
database_license = [('Veeam Backup VM', 02), ('VMware VM', 01)]
for product, license_id in annotation['license']:
if license_id in database_license:
print "do nothing"
else:
del annotation['license']
annotation['license'] = database_license
change = True
if change == True:
annotation['license'] = license_check
change_annotation(vm_mor, annotation)
change = False
由于某种我似乎无法修复的原因,它不会在列表 database_licenses 中找到值 license_id,它只是执行 else,而不是什么都不打印。
有什么想法吗?
我想使用 in 是因为它们可能会出现故障,因此如果您遍历两者并使用 if ths id == that id 它并不总是有效..
这是工作代码:
if str(vm_mor) == vm['config.annotation']:
annotation= pickle.load(open(str(vm_mor), "rb"))
print annotation
sql_check_exist = '''select a.vm_mor, b.license_id, c.product from vms a , vm_licenses b, licenses c where a.vm_id = b.vm_id and b.license_id = c.license_id and a.vm_mor = '%s' ''' % str(vm_mor)
cursor_exist.execute(sql_check_exist)
database_license = []
for vm_mor, license_id, product in cursor_exist:
database_license.append((product,license_id))
checklist_database_license = [int(i[1]) for i in database_license] #make a list of 2nd element of all the tuples in the database_license list
check_me = annotation['license']
for product, license_id in check_me:
if license_id in checklist_database_license:
print "do nothing"
else:
del annotation['license']
annotation['license'] = database_license
change = True
if change == True:
change_annotation(vm_mor, annotation)
change = False
else:
print vm['config.name']
pickle_mor(vm_mor,vm)
【问题讨论】:
-
附带说明,您几乎肯定不想写
01和02。在 Python 2.7 中,前导0表示它们是八进制数——前 7 位并没有什么不同,但是一旦你到达08就会出错——而且更糟糕的是,对于010它似乎可以工作,但值错误。 (另外,在 Python 3.x 中,0前缀是非法的。) -
还有一点小提示:不要写
if change == True:,只写if change:(除非你真的需要将True与其他真实值区分开来——它偶尔会出现,但它是非常罕见)。 -
@abarnert 是的,我输入 01 和 02 这不是真实数字,但不想泄露客户数据。感谢您提供有关如果更改的提示:这是否意味着如果更改为假:不会赶上?
标签: python list loops python-2.7 dictionary