简体   繁体   English

从txt文件创建的列表中编辑字典列表

[英]Editing a list of dictionaries from a list created from a txt file

I am trying to exclude and remove some dictionaries from a list. 我正在尝试从列表中排除并删除一些词典。 I have searched for awhile through the site and haven't found anything specific to this. 我已经在该网站上搜索了一段时间,但未找到与此相关的任何内容。 The list of dictionaries was created from a txt file located: http://s000.tinyupload.com/?file_id=48953557772434487729 字典列表是通过以下txt文件创建的: http ://s000.tinyupload.com/?file_id= 48953557772434487729

I'm trying to sort out and exclude the things I don't need. 我正在尝试找出并排除我不需要的东西。 I thought my syntax was right, but apparently not. 我以为我的语法正确,但显然不正确。

I only included necessary code to cut down on the clutter. 我只包含了必要的代码以减少混乱。 I am having problems at the action_genre point and excluding and deleting the dictionaries there. 我在action_genre点遇到问题,并在那里排除和删除字典。 When prompted enter "s" and then "a" to access those two menus. 出现提示时,输入“ s”,然后输入“ a”以访问这两个菜单。

def load_movies():
    global movies_list
    movies_list= []
    file_ref = open("movies.txt", 'r')
    line = file_ref.readline()
    for line in file_ref:
        line = line.strip()
        current = {}
        if line == '':
            break
        movie_data = line.split("\t")
        current["title"] = movie_data[0]
        current["year"] = movie_data[1]
        current["length"] = movie_data[2]
        current["rating"] = movie_data[3]
        current["action"] = int(movie_data[4][0]) == 1
        current["animation"] = int(movie_data[4][1]) == 1
        current["comedy"] = int(movie_data[4][2]) == 1
        current["drama"] = int(movie_data[4][3]) == 1
        current["documentary"] = int(movie_data[4][4]) == 1
        current["romance"] = int(movie_data[4][5]) == 1
        movies_list.append(current)
        del current
    file_ref.close()


def menu():
    movie_selector =("Movie Selector - Please enter an option below:\nL - List all movies\nY - List all movies by year\n"
                "T - Search by title\nS - Search by genre, rating, and maximum length\nQ - Quit the program\nOption:")
    movie_selector_input = input(movie_selector).upper()

    if movie_selector_input == "L":
        list_movies()
    if movie_selector_input == "Y":
        list_by_year()
    if movie_selector_input == "T":
        search_by_title()
    if movie_selector_input == "S":
        search()
    if movie_selector_input == "Q":
        print("Thanks for using my program! Goodbye.")
        exit()
else:
    print("Invalid input")
    print("Please try again")
    print()
    return menu()

def search():
    genre_input = input("Please make a selection from the following genres.\n(Action(A), Animation(N), Comedy(C), "
                    "Drama(D), Documentary(O), or Romance(R)):").lower()
    if genre_input == 'a':
        action_genre()
    elif genre_input == 'n':
        animation_genre()
    elif genre_input == 'c':
        comedy_genre()
    elif genre_input == 'd:':
        drama_genre()
    elif genre_input == 'o':
        documentary_genre()
    elif genre_input == 'r':
        romance_genre()
    else:
        print("Invalid genre")
        print()
        menu()

#this is where I can't get the syntax to work
def action_genre():
    for current in movies_list:
        if current["action"] == "False":
            del current
            break
        for i in movies_list:#using this to test output
            print(i)

load_movies()
menu()

I'm narrowing down the list by excluding things that don't fit the parameters. 我通过排除不适合参数的内容来缩小列表的范围。 In the action_genre function, I'm trying to delete all the dictionaries that don't equal current["action"] == True. 在action_genre函数中,我试图删除所有不等于current [“ action”] == True的字典。 I've tried using "True" and "False" as strings, as well as the bools True and False for comparisons, and still an error. 我尝试使用“ True”和“ False”作为字符串,以及布尔值True和False进行比较,仍然是一个错误。 Unfortunately, I have to use the Boolean logic per my professors directions. 不幸的是,我必须按照教授的指导使用布尔逻辑。

His eg: Professor's example. 的例子教授的榜样。 Apparently since I'm new I can't embed images. 显然,由于我是新手,所以无法嵌入图像。 :/ :/

I'm in programming 101, so thank you for your patience as I learn this, and thank you in advance for the help. 我正在编程101,因此,感谢您在我学习过程中的耐心配合,并感谢您的帮助。

You are trying to compare a string with a boolean . 您正在尝试将stringboolean进行比较。 Look at the following: 请看以下内容:

a= 1==1
print a
True

print type(a)
<class 'bool'> # a is a boolean

b='True' #assign string 'True' to b
print type(b)
<class 'str'>

print a==b #compare boolean True to string 'True'
False

b = True # assign boolean True to b
print a==b #compare boolean True to boolean True
True

so you need if current["action"] == False instead of if current["action"] == "False" 因此您需要if current["action"] == False而不是if current["action"] == "False"

Okay, so the issue runs a bit deeper than the if condition being incorrect. 好的,所以问题要比if条件不正确的问题更深。 In get_action() you effictively do not modify the actual movies_list object, but rather the local variable current , as proven by this simple test: get_action()您实际上没有修改实际的movies_list对象,而是修改了本地变量current ,如以下简单测试所示:

def action_genre():
    for current in movies_list:
        print(current)
        if not current["action"]:
            del current
        print(current)

The second print(current) will result in an UnboundLocalError saying that current does not exist anymore, while in movies_list the entry it just deleted continues to exist. 第二个print(current)将导致UnboundLocalErrorcurrent不再存在,而在movies_list中刚刚删除的条目仍然存在。 But in general, using del in loops indeed causes problems because that's how iterables and del itself behave. 但是总的来说,使用del in循环确实会引起问题,因为这就是可迭代对象和del本身的行为。 I encourage you to read up more on this on other sources or SO if you wish, like here . 如果您愿意,我鼓励您阅读其他来源或SO的更多内容,例如此处

Using the answer from the provided link above, we can use list comprehension to filter the movies: 使用上面提供的链接中的答案,我们可以使用列表理解来过滤电影:

def action_genre():
    filtered_movies_list = [movie for movie in movies_list if movie['action']]
    print(filtered_movies_list)

This creates a new list (so it does not modify movies_list ), which includes all dictionary entries where item['action'] == True . 这将创建一个新列表(因此它不会修改movies_list ),其中包括item['action'] == True所有字典条目。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM