从列表列表中的目标打印行

2024-09-29 18:57:20 发布

您现在位置:Python中文网/ 问答频道 /正文

第一个块是这个程序中使用的输入文件(只是一个.txt文件)。 在“SearchByTitle”函数中,它可以正确地识别目标是否在列表中,并成功地将其打印出来,但是,它只会打印出实际的目标单词。有没有办法让它把整行打印出来?例如,如果搜索'Sempiternal',它是否可以返回Sempiternal,给我带来Horizon,Metalcore,14.50,而不仅仅是目标词? 另外,当按价格排序时,它只返回比目标值小的最接近的价格,而不是所有小于目标值的价格。你知道吗

任何朝着正确方向的推动都是很好的,我已经搞了好几天了。你知道吗

输入文件:

Sempiternal,Bring Me The Horizon,Metalcore,14.50
Badlands,Halsey,Indie Pop,19.95
Wildlife,La Dispute,Post Hardcore,9.60
Move Along,The All American Rejects,Punk Rock,10.20

功能:

def createDatabase(CD):
    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


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: ")
    title = [item[0] for item in aList]
    for item in title:
        if target in item:
            print("Title name found in database: " + target)
            return aList
        print("Title not found")
        return None


def FindByPrice(aList):
    target = float(input("Enter Maximum Price: "))
    price = [item[3] for item in aList]
    for item in price:
        if item <= target:
            print(item)
            return aList
    print("Artist not found")
    return None

Tags: 文件intarget目标forreturndefline
2条回答

你可以试试下面的方法

def find_by_title(rows):
    query = input('Title: ')
    found = [row for row in rows if row[0] == query]
    return found[0] if found else None

如果它是一个大名单,你想打破一旦你找到它,那么

for row in rows:
    if row[0] == query:
        found = row
        break

您的所有功能都可以在一定程度上得到清理。请不要使用camelCase函数和变量名,请使用snake_case。前者非常令人讨厌。你知道吗

您应该使用熊猫套餐:

import pandas as pd
df = pd.read_csv(your_input_file)

df[df[0]=='Sempiternal']

pandas的思想是将文件存储在一个数据帧中,那么对文件的操作要比使用循环简单得多(而且效率更高)。 只需记住,数据帧将存储到RAM中,所以要小心处理大量的输入文件。你知道吗

相关问题 更多 >

    热门问题