1. 程式人生 > >Python學習筆記_二維數組的查找判斷

Python學習筆記_二維數組的查找判斷

位數組 在二維數組中 有一個 not found 一個 for fin 行數 找到

在進行數據處理的工作中,有時只是通過一維的list和有一個Key,一個value組成的字典,仍無法滿足使用,比如,有三列、或四列,個數由不太多。

舉一個現實應用場景:學號、姓名、手機號,可以再加元素

這裏我想到的一個辦法是采用二維數組來處理。

軟件環境:

1.OS:Win10 64位

2.Python 3.7

參考代碼,不多解釋,下面代碼可執行。

#! -*- coding utf-8 -*-
#! @Time  :2019/3/10 
#! Author :Frank Zhang
#! @File  :Test.py
#! Python Version 3.7

#判斷某個元素是否在二位數組中存在,存在則返回True,不存在,則返回False
list=[] def main(): list_a=[a1,a2,a3] if list_a not in list: list.append(list_a) list_b=[b1,b2,b3] if list_b not in list: list.append(list_b) list_c=[c1,c2,c3] if list_c not in list: list.append(list_c) list_d=[
d1,d2,d3] if list_d not in list: list.append(list_d) list_e=[e1,e2,e3] if list_e not in list: list.append(list_e) list_f=[c1,c2,c3] if list_f not in list: list.append(list_f) print(list) strTmp="b1
" print("The search str is :" + strTmp) print("====================example 1=======================") if Find1(strTmp,list)==True: print("It‘s found") else: print("It‘s not found") print("====================example 2=======================") list_r=Find2(strTmp,list) if not list_r: print("The target list is not found.") else: print(list_r) print("====================example 3=======================") list_r=Find3(strTmp,list,1) if not list_r: print("The target list is not found.") else: print(list_r) #判斷是否存在某個元素,如果存在,則返回True,不存在,則返回False def Find1(target,array): # 不存在數組則直接返回 if not array: return False # 二維數組的行 row = len(array) # 二維數組的列 col = len(array[0]) # 二層循環遍歷二維數組 for i in range(row): for j in range(col): # 如果目標值等於數組中的值,則找到 if target == array[i][j]: return True # 數組遍歷結束後仍未找到 return False #判斷某個元素是否存在,存在則返回該元素存在的一維數組 def Find2(target,array): if not array: return False # 二維數組的行 row = len(array) # 二維數組的列 col = len(array[0]) # 二層循環遍歷二維數組 for i in range(row): for j in range(col): # 如果目標值等於數組中的值,則找到 if target == array[i][j]: return array[i] # 數組遍歷結束後仍未找到 return False def Find3(target,array,searchCol): if not array: return False # 二維數組的行 row = len(array) # 二維數組的列 col = len(array[0]) # 二層循環遍歷二維數組 for i in range(row): # 如果目標值等於數組中的值,則找到 if target == array[i][searchCol]: return array[i] # 數組遍歷結束後仍未找到 return False if __name__=="__main__": main()

其中分三種情況:

1.判斷某個元素是否在二位數組中。在則返回True,不在則返回False

2.判斷某個元素是否在二維數組中,在則返回該元素所在的行,作為一維數組,可相應獲取其它該一維數組裏其它的元素。

3.判斷某個元素是否在二維數組指定列中,在則返回該元素所在的行。

Python學習筆記_二維數組的查找判斷