此作业具有内置的IDLE,因此必须对此进行处理。
我不知道版本更新,但假设它是2.1-2.7
我尝试了set_a & set_b
和set.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),
)
main()
此外,我尝试了此方法,但它只是比较第一个方法。
答案 0 :(得分:0)
您的解决方案是为迭代中的项目和列表的名称使用相同的变量名称。要解决您的解决方案,您可以执行以下操作:
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]
答案 1 :(得分:0)
您的in_both_lists
循环正在重新定义myFavSports
和yourFavSports
,因为您在循环的每一侧使用相同的变量名。
Python循环语法定义为:
for item in list:
当前正在使用
for list in list:
因此list
被重新定义为item
的值。