繁体   English   中英

比较 python 中两个列表的元素

[英]Comparing elements of two lists in python

所以我需要比较 python 中 2 个列表的元素,如果它们有超过 15 个共同元素,它应该显示一条消息。我尝试使用 for 循环遍历这些列表,并比较该列表中的每个元素,并且如果它们相等,我做了一个计数器来计算我的正确答案,如果它们超过 15 则显示消息“你通过了”。但它根本不起作用,它总是说我无论如何都通过了 这是代码:

for j in answerList:
    for k in answers:
        if(k==j):
            nr+=1
if(nr>15):
    print("You passed")
else:
    print("You failed")

因为对于answerListanswer是重复的,所以你应该使用zip()

for j,k in zip(answerList,answers):
    if(k==j):
        nr+=1
if(nr>15):
    print("You passed")
else:
    print("You failed")

nr=sum(k==j for j,k in zip(answerList,answers))

通过考虑len(answers) == len(answerList) ,您可以zip()两个列表并在一行中执行比较

n = len([*filter(lambda x: x[0] == x[1], zip(answerList, answers))])

if n > 15:
     print("You passed")
else:
     print("You failed")

仅供参考:在您的情况下,时间复杂度为O(len^2) ,在这种情况下,时间复杂度为 O O(n)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM