2016-05-12 35 views
-1

所以我需要搜索一個項目是否在列表的第一列,如果是,打印該項目。我必須使用函數來做到這一點。在列表和功能列表中搜索

CD = input("Enter name of CD database: ")  

def createDatabase(CD):  #opens and creates list 
    aList = [] 
    file = open(CD) 
    for line in file: 
     line = line.rstrip().split(",") #strip \n and split at , 
     aList.append(line)  #add lines into formerly empty aList 
    for i in range(len(aList)): 
     aList[i][3] = float(aList[i][3]) #override line for price to be float 
    return aList 

aList = createDatabase(CD) 

def PrintList(aList): 
    for line in aList: 
     album = str(line[0]) 
     artist = str(line[1]) 
     genre = str(line[2]) 
     price = str(line[3]) 
     print("Album: " + album + " Artist: " + artist + " Genre: " + genre + " Price: $" + price) 
    return 


def FindByTitle(aList): 
    target = input("Enter Title to Search: ") 
    for item in aList: 
     if target in aList: 
      print(target) 
     else: 
      print ("Title not found") 
    return aList 

PrintList(FindByTitle(aList)) 

我從這個讓我的輸出是

Enter name of CD database: CD.txt 
Enter Title to Search: Sempiternal 
Title not found 
Title not found 
Title not found 
Title not found 
Album: Sempiternal Artist: Bring Me The Horizon Genre: Metalcore Price: $14.5 
Album: Badlands Artist: Halsey Genre: Indie Pop Price: $19.95 
Album: Wildlife Artist: La Dispute Genre: Post Hardcore Price: $9.6 
Album: Move Along Artist: The All American Rejects Genre: Punk Rock Price: $10.2 

,我不完全知道該怎麼做或解決我的搜索功能。任何幫助將非常感謝。

+0

產生列出了一些樣本數據和輸入(與字符串替換'input'表達式)添加到你的問題,所以我們可以運行代碼。 –

+1

'如果aList中的目標:'不正確。 '如果目標在項目中:' – ssm

回答

0

一旦找到匹配項,您可以儘早返回您的FindByTitle函數。如果控制流量超出循環範圍,您可以確保沒有滿足標準並返回失敗。

def FindByTitle(aList): 
    target = input("Enter Title to Search: ") 
    for item in aList: 
     if target in item: 
      print(target) 
      return aList # return here 
    print("Title not found") 
    return None 

如果你需要返回所有可能的列表,保持可用於查找是否有一個計數至少有一個匹配

+0

工作完美,但是,有沒有辦法我可以讓它只搜索第一組元素,因爲到目前爲止它打印的是正確的輸出,但沒有找到'標題未找到'三次列表 – Staylor742

+0

其他行的實際上得到了排序。 但是最後一個問題,有沒有辦法讓我只打印目標?因爲它仍然在打印目標以及整個列表之後。 – Staylor742

+0

簡單地省略你最後的打印語句。 – bashrc

0

在功能FindByTitle在第4行 因你而改變alistitem正在尋找在嵌套列表ALIST目標,而不是搜索通過循環

def FindByTitle(aList): 
target = input("Enter Title to Search: ") 
for item in aList: 
    # change here 
    if target in item: 
     print(target) 
    else: 
     print ("Title not found") 
return aList