Python 在数组中插入缺失的元素

Python insert missing elements in array

我有一个格式如下的数组:

[(u'iapsetting', 0), (u'iap-mms',0)]

数组必须只包含这种类型的元组:

(u'mmssetting', 0) or (u'iapsetting', 0) or (u'iap-mms', 0)

我的第一个数组显然缺少 (u'mmssetting',0) 但它可以 missing/existing 元组的许多不同组合。

我正在努力寻找一种方法来添加正确的缺失元组。该数组必须始终仅包含 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))

任何帮助将不胜感激,因为可能有更好的方法来做到这一点。谢谢。

萨拉

而不是使用 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 不同(在这种情况下也更好),请参阅其他答案

试试这个:

existing = set(x[0] for x in setup)
for expected in ('iapsetting', 'mmssetting', 'iap-mms'):
    if expected not in existing:
        setup.append((expected, 0))

我觉得集合最能体现这个逻辑。使用集合理解来提取字符串。

 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)

你做错的主要有两点:

  • 您在循环内初始化了标志。
  • 您在完成对整个数组的循环之前开始添加缺少的设置。

    # 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))