如果是python中的/ else语句

时间:2018-02-12 22:17:03

标签: python

我如何在列表中使用if和else语句?就像我有一个预制列表然后用户输入他们的列表如何将它显示到它显示的位置我们输入相同的答案。 这是作业:

  

选择一个类别并列出您最喜欢的五件事。建议的类别包括您最喜欢的:演员,书籍,汽车或您选择的其他内容。

     

询问用户所选类别中的收藏夹。

     

通过创建列表,循环和if语句,打印一条消息,让用户知道他们的收藏夹是否与列表中的收藏夹匹配。

     

将整个列表整齐地打印到屏幕上。请务必为每个项目编号。

     

编写此程序的伪代码。请务必包含任何所需的输入,计算和输出。

这是我目前的代码:

def main():

    print("What are your five favorite cars?")

    favoriteCarOne = input("What is your first favorite car?")
    favoriteCarTwo = input("What is your second favorite car?")
    favoriteCarThree = input("What is your third favorite car?")
    favoriteCarFour = input("What is your fourth favorite car?")
    favoriteCarFive = input("What is your fifth favorite car?")

    userCarList = [favoriteCarOne, favoriteCarTwo, favoriteCarThree, favoriteCarFour, favoriteCarFive]
    daltonCarList = ["Shelby", "Dodge HellCat", "Nissian GT-R R34", "Ford Focus RS", "Corvette ZR1"]

    for n in range(0, len(userCarList)):
        print(str(n) + " " + userCarList[n])


    daltonLength = len(daltonCarList)
    userLength = len(userCarList)

    if (userCarList == daltonCarList):
        print("Cool! We like the same cars!")
        print

    else:
        print("Those are cool cars!")
        print

    print("These are my favorite cars!")
    print(daltonCarList)
    print


main()

2 个答案:

答案 0 :(得分:0)

List comprehensions是你的朋友!

matched = [i for i in daltonCarList if i in userCarList]

if matched:
    print "Cool, we liked some of the same cars!"
    print matched

此代码将生成一个包含来自dalton和user的匹配项的新列表。

如果您想查看两个列表是否完全相同,那么您的答案就是here

答案 1 :(得分:0)

Python可以很好地比较两个列表:

a = ["Shelby", "Dodge HellCat", "Nissian GT-R R34", "Ford Focus RS", "Corvette ZR1"]
b = ["Shelby", "Dodge HellCat", "Nissian GT-R R34", "Ford Focus RS", "Corvette ZR1"]

if a == b:
    print("They are the same")
else:
    print("They are different")

# Outputs: They are the same

但是,如果它们的顺序不同,则不起作用:

a = ["Shelby", "Dodge HellCat", "Nissian GT-R R34", "Ford Focus RS", "Corvette ZR1"]
b = ["Dodge HellCat", "Shelby", "Nissian GT-R R34", "Ford Focus RS", "Corvette ZR1"]

if a == b:
    print("They are the same")
else:
    print("They are different")

# Outputs: They are different

根据要求,您似乎需要检查两个列表中是否存在所有元素,但不一定按顺序排列。最简单的方法是使用两个set,但似乎需要使用循环。

相反,也许可以尝试使用not in关键字来检查汽车是否存在。这方面的一个例子是:

for car in their_cars:
    if car not in my_cars:
        print("Oh no, a car that's not in my list")

警告,这不是完整的。假设有人进入"Shelby" 5次,它会通过。所以你需要扭转它并向后检查。