有两个最喜欢的运动列表。一个是自动化的,一个是用户输入的。找到路口

There are two lists of favorite sports. One's automated and one's user input. Find the intersection

这项作业有一个内置的 IDLE,所以它必须处理它。 我不知道版本更新,但我假设它是 2.1-2.7 我尝试了 set_a & set_bset.intersect,但我使用的软件不支持。 我将尝试合并 if 和 for 循环。 我有一个粗略的想法,将每个列表元素与另一个列表元素进行比较,直到所有元素都被比较过,所以它有任何相似之处,只是说出有多少相似之处。

代码如下:

#Khushi Desai
#7/20/18
#Purpose: To see if me and the user have any similarities

def main():

myFavSports = ["Gymnastics", "High Jumping", "Table Tenis", "Golf", "Ice Skating"]
length = len(myFavSports)

print(" My Favorite Sports")
print("--------------------")
for n in range(0, len(myFavSports)):
    print(str(n + 1) +". "+ myFavSports[n] + "!")


favSport1 = input("What is your first favorite sport?")
favSport2 = input("What is your second favorite sport?")
favSport3 = input("What is your third favorite sport?")
favSport4 = input("What is your fourth favorite sport?")
favSport5 = input("What is your fifth favorite sport?")

yourFavSports = [favSport1, favSport2, favSport3, favSport4, favSport5]


print("")
print(" Your Favorite Sports")
print("----------------------")
for n in range(0, len(yourFavSports)):
    print(str(n + 1) +". "+ yourFavSports[n] + "!")


in_both_lists = []
for myFavSports in myFavSports:
    for yourFavSports in yourFavSports:
        if myFavSports == yourFavSports:
            in_both_lists.append(myFavSports)

print "We both love {}: {}".format(
    len(in_both_lists),
    ", ".join(in_both_lists),
)

主要()

另外,我试过这个方法,但它只是比较第一个。

您的解决方案对迭代中的项目和列表名称使用了相同的变量名称。要修复您的解决方案,您可以这样做:

in_both_lists = []
for mySport in myFavSports:
    for yourSport in yourFavSports:
        if mySport == yourSport:
            in_both_lists.append(mySport)

或者您可以简单地这样做:

in_both_lists = [sport for sport in yourFavSports if sport in myFavSports]

您的 in_both_lists 循环正在重新定义 myFavSportsyourFavSports,因为您在循环的每一端都使用相同的变量名。

Python循环语法定义为:

for item in list:

您目前正在使用

for list in list:

所以 list 被重新定义为 item.

的值