【问题标题】:How to get list([a,2],[a,1],[a,3]) with the highest number([a,3])如何获取列表([a,2],[a,1],[a,3])的最高数字([a,3])
【发布时间】:2019-05-21 16:01:06
【问题描述】:

我有一个

list=[[a,2],[a,1],[a,3],[b,5],[b,7],[b,6],[c,20],[c,23],[c,30]].

如何获得每个字母的最大数字列表?并且该列表将其附加到包含每个字母的最高数字的另一个列表中?

我尝试过使用以下代码,但我是 python 编程的新手,我对数据结构或编程了解不多。

for letter in range(len(final)):
    array1=[]
    array2=[]
    highestvalue=0
    if final[letter][0] == final[letter+1][0]:
        if final[letter][2] < final[letter+1][2]:
            highestvalue=final[letter+1][2]
            array1.append(final[letter][0])
            array1.append(highestvalue)
            array2.append(array1)

有没有办法将 [[a,3],[b,7],[c,30]] 排除在列表之外?

[编辑] 实际上,我的列表是 [[a,abc,2],[a,def,1],[a,ghi,3],[b,jkl,5],[b,lmn,7],[b,opq ,6],[c,rst,20],[c,vwx,23],[c,yzz,30]]。

我期望创建一个存储变量 [[a,ghi,3],[b,lmn,7],[c,yzz,30]] 的列表。如何使用第二个元素以及字母和最大值创建列表?

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    既然你标记了pandas

    pd.DataFrame(l).groupby(0).max().reset_index().values.tolist()
    Out[535]: [['a', 3], ['b', 7], ['c', 30]]
    

    【讨论】:

      【解决方案2】:

      您可以使用itertools.groupby 按字母对子列表进行分组,并在每个组中查找最大值:

      from operator import itemgetter as g
      from itertools import groupby
      
      [max(v, key=g(1)) for k, v in groupby(l, g(0))]
      # [['a', 3], ['b', 7], ['c', 30]]
      

      【讨论】:

      • 你已经在使用itemgetter,去镇上from operator import itemgetter as g; from itertools import groupby; [max(v, key=g(1)) for k, v in groupby(l, g(0))]
      【解决方案3】:
      >>> foo = [['a', 2],['a', 1],['a', 3],
                 ['b', 5],['b', 7],['b', 6],
                 ['c', 20],['c', 23],['c', 30]]
      >>> print({key:value for key, value in sorted(foo)})
      {'a': 3, 'b': 7, 'c': 30}
      

      【讨论】:

      • 应该这样做[*map(list, dict(sorted(foo)).items())]
      • 啊,在这里使用排序的好主意
      【解决方案4】:

      您可以使用简单的 Python 生成器来解决它:

      lst=[['a',2],['a',1],['a',3],['b',5],['b',7],['b',6],['c',20],['c',23],['c',30]]
      [max(filter(lambda x: x[0] == elem, lst), key=lambda x: x[1]) for elem in set([e[0] for e in lst])]
      

      会还给你:

      [['c', 30], ['b', 7], ['a', 3]]

      【讨论】:

        【解决方案5】:

        首先,将您的列表分成单独的列表,每个字母对应一个。 然后构建第二个元素的列表并取其中的max

        另一种可能性是建立一个以字母为键的dict;每个元素的值是你看到的那个字母的最大值。

        你能在那里接受它吗?如果没有,我建议与当地人一起研究逻辑,因为 Stack Overflow 不是教程网站。

        【讨论】:

          【解决方案6】:

          熊猫解决方案:

          pd.DataFrame(l).sort_values([0, 2]).drop_duplicates(subset=[0], keep='last').values.tolist()
          
          Out[23]: [['a', 'ghi', 3], ['b', 'lmn', 7], ['c', 'yzz', 30]]
          

          【讨论】:

            【解决方案7】:

            您可能希望将临时最大值存储在字典中。这样你仍然可以用O(n) 复杂性来解决它。看看这个简单的例子:

            mylist = [['a','abc',2],['a','def',1],['a','ghi',3],['b','jkl',5],['b','lmn',7],['b','opq',6],['c','rst',20],['c','vwx',23],['c','yzz',30]]
            
            myres = []
            mymax = {}
            
            for l in mylist:
                # corresponds to 'a', 'b', 'c', ...
                k = l[0]
            
                # if your identifier is not already stored
                # or the last value of your array is greater than the one that is already stored
                if not k in mymax or l[-1] > mymax[k][-1]:
                    # apply a new maximum
                    # *after first iteration it holds -> {'a': ['a','abc',2]}
                    mymax[k] = l
            
            # is used to convert back to a list, you may as well skip it if not needed
            for _, v in mymax.items():
                myres.append(v)
            
            # prints [['a', 'ghi', 3], ['b', 'lmn', 7], ['c', 'yzz', 30]]
            print(myres)
            

            希望对你有帮助!

            【讨论】:

              【解决方案8】:

              您应该考虑使用一个地方来存储(字典)每个字母遇到的最高值。

              然后浏览列表,将存储中的值与字母的新值进行比较。

              list=[[a,2],[a,1],[a,3],[b,5],[b,7],[b,6],[c,20],[c,23],[c,30]]
              storing_maximum={}
              for x,y in list:
                  if x in storing_maximum:
                      storing_maximum[x] = max(storing_maximum[x],y)
                  else:
                      storing_maximum[x] = y
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-09-10
                • 1970-01-01
                • 1970-01-01
                • 2023-04-04
                • 1970-01-01
                • 2021-12-22
                • 2012-11-23
                • 2020-02-15
                相关资源
                最近更新 更多