python中的If/else语句

2024-04-29 16:55:19 发布

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

如何在列表中使用and if and else语句?比如,如果我有一个预先制作的列表,那么一个用户输入他们的列表,我将如何使它显示在那里,我们输入了相同的答案。 任务如下:

Pick a category and make a list of your five favorite things. Suggested categories include your favorite: actors, books, cars, or something else of your choosing.

Ask the user what their favorites are in your selected category.

By creating a list, a loop, and if statements, print a message that lets the user know if their favorites matches the ones on your list.

Neatly print your entire list to the screen. Be sure to number each item.

Write the pseudocode for this program. Be sure to include any needed input, calculations, and output.

这是我目前的代码:

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()

Tags: andtheinputyourifiscarcars
2条回答

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

这段代码将生成一个新的列表,其中包含来自道尔顿和用户的匹配项。你知道吗

如果你想看看两个列表是否完全相同,你的答案是here

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次,它就会通过。所以你得倒过来检查一下。你知道吗

相关问题 更多 >