为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪9158850 2023-10-06 18:31:14
我是 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)对不起我的英语不好
查看完整描述

4 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

返回的唯一原因-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))

哪一个“更好”是个人喜好的问题。)


查看完整回答
反对 回复 2023-10-06
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

逐项比较,如果大于则加1point


list1 = [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


查看完整回答
反对 回复 2023-10-06
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

积分总和:


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


查看完整回答
反对 回复 2023-10-06
?
Helenr

TA贡献1780条经验 获得超3个赞

这将是我对你的问题的解决方案:


    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 语句之后打印一些内容,该语句存在该函数)希望有帮助,拉尔斯


查看完整回答
反对 回复 2023-10-06
  • 4 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信