簡體   English   中英

檢查列表列表的函數具有0到n之間的所有整數元素,並且列表是否都具有給定的長度?

[英]Function to check list of lists have all integer elements between 0 and n and lists are all of given length?

我想檢查以下的元組列表:

C = [[2,2,1,3],[2,2,2,1],[3,3,0,3],[0,2,0,3]] D = [[2,2 ,1、3],[2、2、2、1],[3、3、0、3]]

我想檢查列表的長度是否為n,其中n> 0且為整數,並且該列表也具有長度為n的列表。 檢查條目是0到n-1之間的整數

條件:

  • 清單的長度為n
  • 列表中僅包含數字元素列表

  • 列表中的列表長度為n

  • 里面的列表具有介於0和n-1之間的元素

  • 列表的元素都是整數

因此,對於C來說,列表的長度為4,它的列表長度為4,並且都是0到4之間的整數,因此該函數應輸出true。

對於D,這將是錯誤的,因為列表的長度為3,而列表中的長度為4。

誰能幫忙嗎?

我已經嘗試過isinstance命令,但是其中的許多代碼使我的代碼變得非常混亂。 有沒有更簡單的方法可以做到這一點?

到目前為止,這是我所沒有的。

def checklist(X):
    n = len(X) #check len
    n = int #check it is int
    if n>0: #condition n>0 
        if isinstance(X,list): #check if x is list 
            for i in range(n) :
                if isinstance(X[i],list): #check if the X contains list 
                   a = X[[i]]
                   if isinstance(a, int)



使用嵌套列表理解的all嵌套

C = [[2, 2, 1, 3], [2, 2, 2, 1], [3, 3, 0, 3], [0, 2, 0, 3]]

n = 4

def is_valid(C, n):
    valid_values = range(n)
    return all(all(x in valid_values for x in l) and len(l) == n for l in C) and len(C) == n

print is_valid(C, n)

輸出:

True

由於已使用NumPy對此進行了標記,因此這是僅NumPy的解決方案:

# input for positive case
C = [[2, 2, 1, 3], [2, 2, 2, 1], [3, 3, 0, 3], [0, 2, 0, 3]]
c_arr = np.array(C)  # convert to numpy array

# input for negative case
D = [[2, 2, 1, 3], [2, 2, 2, 1], [3, 3, 0, 3]]
d_arr = np.array(D)

# range to check for
n = 4

將所有需要的條件並入Python函數(OP要求):

def check_condition(n, arr):
     if arr.shape[0] == n and np.all(arr >= 0) \
        and np.all(arr < n) and arr.dtype == np.int:
         return True
     else:
         return False

# checking for positive case        
check_condition(n, c_arr)   # returns `True`

# checking for negative case        
check_condition(n, d_arr)   # returns `False`

我建議您將注意力集中在此類的可讀性和簡單性上。 當試圖滿足多個條件時,很容易迷失方向;如果以后嘗試變得更聰明或盡可能簡潔,那么當您稍后回到代碼時,很難弄清楚自己在做什么。 如果將需求分開和明確地列出,則可以更輕松地看到正在正確測試它們。 盡早返回可以使您的代碼縮進更少,並且更易於閱讀。

def element_is_good(element, length):
    return isinstance(element, int) and 0 <= element < length

def sublist_is_good(sublist, length):
    return (isinstance(sublist, list)
            and len(sublist) == length
            and all(element_is_good(element, length) for element in sublist))

def list_of_lists_is_good(list_of_lists):
    n = len(list_of_lists)
    return n > 0 and all(sublist_is_good(sublist, n) for sublist in list_of_lists)

這比其他解決方案要長一些,但是我認為它更易於閱讀,更易於測試和更易於維護。 (它也滿足您列出的所有要求; DroiX86將接受一個空列表或字典列表,而kmario23將接受一個空數組或元組列表。我省略了您的“ n is int”要求,因為僅len函數返回整數。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM