我有一个以下格式的数组:
[(u'iapsetting', 0), (u'iap-mms',0)]
数组必须只包含此类型的元组:
(u'mmssetting', 0) or (u'iapsetting', 0) or (u'iap-mms', 0)
我的第一个阵列显然错过了(你的设置',0),但它可能有许多不同的组合丢失/现有元组。
我正在努力寻找添加正确缺失元组的方法。该数组必须始终只包含3个元组。
这是我到目前为止所做的,但它没有按预期工作:
for type in setup: #setup is the array containing 1,2 or 3 tuples
iap_found = False
mms_found = False
iap_mms_found = False
if type[0]=='iapsetting':
iap_found = True
elif type[0]=='mmssetting':
mms_found = True
elif type[0]== 'iap-mms':
iap_mms_found = True
#Add missing settings
if(iap_found==False):
print("MISSING IAP",setup)
setup.append((u'iapsetting',0))
elif(mms_found==False):
print("MISSING MMS",setup)
setup.append((u'mmssetting',0))
elif(iap_mms_found==False):
print("MISSING IAP-MMS",setup)
setup.append((u'iap-mms',0))
任何帮助将不胜感激,因为可能有更好的方法来做到这一点。谢谢。
萨拉
答案 0 :(得分:4)
试试这个:
existing = set(x[0] for x in setup)
for expected in ('iapsetting', 'mmssetting', 'iap-mms'):
if expected not in existing:
setup.append((expected, 0))
答案 1 :(得分:1)
你做错了主要是两件事:
在完成整个数组的循环之前,您开始添加缺少的设置。
# Initialize flags before entering loop:
iap_found = False
mms_found = False
iap_mms_found = False
for type in setup: #setup is the array containing 1,2 or 3 tuples
if type[0]=='iapsetting':
iap_found = True
elif type[0]=='mmssetting':
mms_found = True
elif type[0]== 'iap-mms':
iap_mms_found = True
#Add missing settings after looping through the whole array:
if(iap_found==False):
print("MISSING IAP",setup)
setup.append((u'iapsetting',0))
if(mms_found==False):
print("MISSING MMS",setup)
setup.append((u'mmssetting',0))
if(iap_mms_found==False):
print("MISSING IAP-MMS",setup)
setup.append((u'iap-mms',0))
答案 2 :(得分:0)
您应该使用
而不是if
... elif
.. elif
if not iap_found:
print("MISSING IAP",setup)
setup.append((u'iapsetting',0))
if not mms_found:
print("MISSING MMS",setup)
setup.append((u'mmssetting',0))
if not iap_mms_found==False:
print("MISSING IAP-MMS",setup)
setup.append((u'iap-mms',0))
if
.. elif
的问题是只有一个分支会被执行。
对于其他解决方案,与if
不同(在这种情况下也更好),请参阅其他答案
答案 3 :(得分:0)
我认为集合最清楚地代表了这种逻辑。使用set comprehension来提取字符串。
REQUIRED_VALUES = {"mmssetting", "iapsetting", "iap-mms"}
input_tuple_list = [(u'mmssetting', 1), (u'iap-mms', 3)]
# set comprehension paired with set difference -- results in {"iapsetting"}
missing_values = REQUIRED_VALUES - {val for val, count in input_tuple_list}
# results in [(u'mmssetting', 1), (u'iap-mms', 3), (u'iapsetting', 3)]
input_tuple_list.extend((val, 0) for val in missing_values)