我的列表比较器不想按照我想要的方式运行

我是 python 的初学者,我有一个任务,winner_round 函数比较两个列表,并计算 Adam 的团队比对手得分更多的游戏中有多少轮。如果两个列表不匹配,则返回 -1 这是我的代码:


def winner_round(list1,list2):

    list1 = [30, 50, 10, 80, 100, 40]

    list2 = [60, 20, 10, 20, 30, 20]

    point = 0

    for i in winner_round(list1,list2):

        if list1>list2:

            return -1

            print(-1)

    for pointA in list1:

        for pointE in list2:

            if pointA > pointE:

                point+=1

        break

    return(point)

    print(point)

对不起我的英语不好


慕田峪9158850
浏览 86回答 4
4回答

呼如林

返回的唯一原因-1是列表的大小是否不同;len在进行迭代之前,您可以使用 O(1) 操作进行检查。之后,只需对列表项进行逐点比较即可。假设list1是亚当和list2他的对手,def winner_round(list1, list2):    if len(list1) != len(list2):        return -1    return sum(x > y for x, y in zip(list1, list2))zip(list1, list2)生成对(30, 60),(50, 20)等。因为True == 1和False == 0(bool是 的子类int),您可以简单地对结果求和,其中的值list1是一对中的较大值。(您还可以使用map,因为作为第一个参数的 2 参数函数允许您将两个列表作为第二个和第三个参数传递,从而无需对实例进行更明确的迭代。提供您需要的zip函数operator.gt:return sum(map(operator.lt, list1, list2))哪一个“更好”是个人喜好的问题。)

蛊毒传说

逐项比较,如果大于则加1pointlist1 = [30, 50, 10, 80, 100, 40]list2 = [60, 20, 10, 20, 30, 20]def winner_round(list1,list2):  point = 0  if len(list1)!=len(list2):    return -1  for i in range(len(list1)):      if list1[i] > list2[i]:          point+=1  return point

慕尼黑8549860

积分总和:list1 = [30, 50, 10, 80, 100, 40]list2 = [60, 20, 10, 20, 30, 20]def winner_round(list1,list2):    if sum(list1) > sum(list2):        return 1    else:        return 2比较每轮:list1 = [30, 50, 10, 80, 100, 40]list2 = [60, 20, 10, 20, 30, 20]def winner_round(list1,list2):    if len(list1) != len(list2): return -1    score1, score2 = 0    for i in range(list1):        if list1[i] > list2[i]:            score1 +=1        else:            score2 +=1    if score1 > score2:        return 1    else:        return 2

Helenr

这将是我对你的问题的解决方案:    def get_points(teamA,teamB):    if len(teamA)!=len(teamB):        print("Both lists have to be of same length.")        return -1    points=0    for i in range(len(teamA)):        if teamA[i]>teamB[i]:            points+=1    print("points:",points)    return points我首先检查两个列表是否具有相同的长度,然后循环遍历两个列表,如果一个列表大于另一个列表,则增加一个计数器。(顺便说一句,您尝试在 return 语句之后打印一些内容,该语句存在该函数)希望有帮助,拉尔斯
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python