删除嵌套列表中的项目

时间:2018-11-29 15:28:45

标签: python python-3.x

我要删除嵌套列表中的字符串

mylist = [
    ["School", "England", "1934"],
    ["House", "Germany", "1845"],
    ["Paris", "France", "1910"]
]

如果用户输入我想要的“学校”,“房屋”或“巴黎”,以便删除整行。我有以下代码:

user = input("What do you want to remove?")
    counter = 0
    for i in mylist:
        for j in i:
            if mylist[counter][0] == user:
                mylist.remove(mylist[counter])
                print(user + " removed!")
        counter = counter + 1

现在的问题是我无法删除mylist中的第三行,只能删除第一行和第二行。我认为问题在于我不确定。

感谢所有帮助!

1 个答案:

答案 0 :(得分:0)

您可以进行列表理解:

mylist = [
    ["School", "England", "1934"],
    ["House", "Germany", "1845"],
    ["Paris", "France", "1910"]
]

user = input("What do you want to remove? ")

mylist = [x for x in mylist if x[0] != user]

样品运行:

What do you want to remove? House
[['School', 'England', '1934'], ['Paris', 'France', '1910']][Program finished]