【问题标题】:Sorting a list of tuples by the first value [duplicate]按第一个值对元组列表进行排序[重复]
【发布时间】:2017-03-21 07:01:21
【问题描述】:

我希望按每个元组中的第一个值对列表进行排序,但是我的代码不会生成任何真正的排序列表,尽管列表的顺序确实发生了变化。我的列表包含具有“PlayerCode”值的元组,它是每个玩家的唯一键。还有“平均分”,即玩家每场比赛的平均得分。我希望按“平均分”对这个列表进行排序,尽管我似乎做错了。这是我的代码

def getKey(item):
        return item[0]
def sortByPoints():
    foundPlayers = []
    with open ('PlayerList.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            foundPlayers.append((row['Average PTS'], row['PlayerCode']))
    print(foundPlayers)
    sortedPlayers = sorted(foundPlayers, key = getKey)

    print (sortedPlayers)

就像我说的,这确实改变了列表的顺序,但不是我正在寻找的方式,我也看不到它已将其更改为的任何真实模式。 我正在使用 python 3.4

这是两个列表的输出

未分类: [('7', '1'), ('8', '2'), ('4', '3'), ('28', '4'), ('0', '5') , ('18', '6'), ('10', '7'), ('9', '8'), ('10', '9'), ('2', '10') , ('4', '11'), ('2', '12'), ('3', '13'), ('4', '14'), ('2', '15') ]

排序: [('0', '5'), ('10', '7'), ('10', '9'), ('18', '6'), ('2', '10') , ('2', '12'), ('2', '15'), ('28', '4'), ('3', '13'), ('4', '3') , ('4', '11'), ('4', '14'), ('7', '1'), ('8', '2'), ('9', '8') ]

【问题讨论】:

  • 请注意,按第一个值排序是元组的默认排序。除此之外,如果没有minimal reproducible example,则不清楚您的问题是什么。
  • 你想根据整数值排序,他们现在是字符串,所以你可以改变 getKey 函数返回 int(item[0])
  • 如果你真的想的话,你可以使用字符串,只需使用float 进行排序 - 请参阅stackoverflow.com/a/17474264/2178980(实际上,上面的注释也可以解决问题)

标签: python list sorting tuples


【解决方案1】:

您可以使用从内置模块operator导入的itemgetter

示例代码:

from operator import itemgetter

tuples = [(10, 3), (1, 4), (5, 4)]
sorted_tuples = sorted(tuples, key=itemgetter(0))

print(sorted_tuples)

输出:

[(1, 4), (5, 4), (10, 3)]

【讨论】:

    【解决方案2】:

    问题是你有字符串,所以它按字母顺序排序。转换为整数:

    foundPlayers.append((int(row['Average PTS']), int(row['PlayerCode'])))
    

    【讨论】:

      【解决方案3】:

      row['Average PTS']row['Player Code'] 返回字符串。 Python 会将字符串与(可能)令人惊讶的结果进行比较

      >>> '6' > '42'
      True
      

      使用int 转换row['Average PTS']row['Player Code']

      【讨论】:

        【解决方案4】:

        你可以使用lambda函数作为key来排序:

        sorted(my_list, key=lambda x: (int(x[1]), int(x[0])))
        

        这里:

        • list 将根据1st 索引处的内容进行排序。如果值相同,list 将根据0th 索引进行排序。
        • 您还需要将tuple 中的值类型转换为int按字典顺序排序。这意味着,对于字符串值,“11”将出现在“2”之前。

        以下是示例:

        >>> my_list = [('7', '1'), ('8', '2'), ('4', '3'), ('28', '4'), ('0', '5'), ('18', '6'), ('10', '7'), ('9', '8'), ('10', '9'), ('2', '10'), ('4', '11'), ('2', '12'), ('3', '13'), ('4', '14'), ('2', '15')]
        >>> sorted(my_list, key=lambda x: (int(x[1]), int(x[0])))                                  
        [('7', '1'), ('8', '2'), ('4', '3'), ('28', '4'), ('0', '5'), ('18', '6'), ('10', '7'), ('9', '8'), ('10', '9'), ('2', '10'), ('4', '11'), ('2', '12'), ('3', '13'), ('4', '14'), ('2', '15')]
        

        【讨论】:

          【解决方案5】:

          这是我的答案。我相信尽可能地维护 OP 的原始代码以尽可能少地做出假设。如果要求有字符串怎么办?此外,尽可能少的额外进口。因此我的解决方案是:

          def sortByPoints():
              foundPlayers = []
              with open ('PlayerList.csv') as csvfile:
                  reader = csv.DictReader(csvfile)
                  for row in reader:
                      foundPlayers.append((row['Average PTS'], row['PlayerCode']))
              print(foundPlayers)
              sortedPlayers = sorted(foundPlayers, key=lambda x: float(x[0]))
              print(sortedPlayers)
          

          删除多余的getKey 函数,并使用lambda 代替以保持整洁。使用float 以防万一将来可能需要它(因为您仅用于比较;使用int 只会限制您并且与float 相比没有优势)。

          我也相信复制和粘贴代码;)


          仅供参考,改变方向:

          sortedPlayers = sorted(foundPlayers, key=lambda x: float(x[0]), reverse=True)
          

          另请注意,如果意图确实仅用于整数,那么您应该按照每个人的建议将您的元素转换为int

          def sortByPoints():
              foundPlayers = []
              with open ('PlayerList.csv') as csvfile:
                  reader = csv.DictReader(csvfile)
                  for row in reader:
                      foundPlayers.append((int(row['Average PTS']), int(row['PlayerCode'])))
              print(foundPlayers)
              sortedPlayers = sorted(foundPlayers, key=lambda x: x[0])
              print(sortedPlayers)
          

          【讨论】:

            猜你喜欢
            • 2012-03-13
            • 2016-03-17
            • 2012-05-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-08
            • 1970-01-01
            相关资源
            最近更新 更多