【问题标题】:My list comparator doesn't want to run the way I want it to我的列表比较器不想按照我想要的方式运行
【发布时间】:2021-01-19 03:21:07
【问题描述】:

我是 python 的初学者,我有一个任务,winner_round 函数比较两个列表,并计算在游戏中有多少轮亚当的球队得分高于对手。如果两个列表不匹配,则返回 -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)

对不起我的英语

【问题讨论】:

标签: python list comparison list-comparison


【解决方案1】:

总分:

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

【讨论】:

  • 感谢您的快速回答!很有用
  • @Fuxy 没问题!
【解决方案2】:

返回-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 == 1False == 0boolint 的子类),您可以简单地将结果相加,其中的值来自list1 是一对中较大的值。

(您也可以使用map,因为第一个参数的2参数函数允许您将两个列表作为第二个和第三个参数传递,从而无需对zip实例进行更明确的迭代。 operator.gt提供你需要的功能:

return sum(map(operator.lt, list1, list2))

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

【讨论】:

  • 感谢您的快速回答!很有用
【解决方案3】:

逐一比较每一项,如果大于另一项,则在point上加1

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

【讨论】:

  • 感谢您的快速回答!很有用
【解决方案4】:

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

    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 语句之后打印一些东西,这存在函数) 希望对你有帮助,拉斯

【讨论】:

  • 感谢您的快速回答!很有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
相关资源
最近更新 更多