如何在列表中使用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()
List comprehensions是你的朋友!你知道吗
这段代码将生成一个新的列表,其中包含来自道尔顿和用户的匹配项。你知道吗
如果你想看看两个列表是否完全相同,你的答案是here
Python可以很好地比较两个列表:
但是,如果它们的顺序不一致,这将不起作用:
根据需求,似乎需要检查两个列表中是否都存在所有元素,但不一定按顺序。最简单的方法可能是使用两个
set
,但是似乎需要使用循环。你知道吗相反,可以尝试使用
not in
关键字来检查汽车是否存在。例如:警告,这不会是完整的。假设有人进入
"Shelby"
5次,它就会通过。所以你得倒过来检查一下。你知道吗相关问题 更多 >
编程相关推荐