【问题标题】:Add to a list based on previous value根据先前的值添加到列表
【发布时间】:2021-05-05 01:47:37
【问题描述】:

我正在尝试将此列表组合在一起

示例输入

M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]

输出

[['a',14,7,16],['b',3,15],['c',22,1,5]]

表示将所有 'a' 值组合在一起,'b'、'c' 等也是如此

【问题讨论】:

  • 字典可以作为输出吗?

标签: python list


【解决方案1】:

下面我举一个字典输出的例子。万一子列表有很多数字,这将解决这个问题并以正确的格式将其排列在正确的部分中。

#看'a'

x = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
dictX = {}
for lsts in x:
    if lsts[0] in dictX.keys():dictX[lsts[0]].extend(lsts[1:])
    else:dictX[lsts[0]] = lsts[1:]           

输出

{'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}

【讨论】:

    【解决方案2】:

    您将需要遍历M1 的元素。您遇到的每个元素都将类似于[ch, num](例如['b', 3])。要将新的num 追加到ch 列表中,您首先需要找到ch 列表,然后将num 追加到ch 列表中。这表明我们应该使用dict,因为我们可以通过chO(1) 中查找。这是一个实现:

    M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
    
    d = dict()
    for ch, num in M1:
      if ch in d:
        d[ch].append(num)
      else:
        d[ch] = [num]
    
    print(d)
    l = list(groups.items())
    print(l)
    # `l` is a list of tuples. The first element of each tuple is the character; the second is the list of `num`s corresponding to that character. For your example, `l` will be:
    # [('a',[14,7,16]),('b',[3,15]),('c',[22,1,5])]
    

    【讨论】:

      【解决方案3】:

      这是使用pandas 的一种方法。

      import pandas as pd
      
      M1 = [['a', 14], ['a', 7], ['a', 16],['b', 3],['b', 15],['c', 22],['c', 1],['c', 5]]    
      df = pd.DataFrame(M1, columns=['id', 'value'])
      
      df = df.groupby(by='id')['value'].apply(list)
      
      >>> df # already grouped as you want
          id
          a    [14, 7, 16]
          b        [3, 15]
          c     [22, 1, 5]
          Name: value, dtype: object
      

      之后,您可以将其转换为像这样的字典

      df = df.to_dict()
      
      >>> df
          {'a': [14, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}
      

      如果需要,也可以列出列表

      l = [[k] + v for k, v in df.items()] 
      
      >>> l
          [['a', 14, 7, 16], ['b', 3, 15], ['c', 22, 1, 5]]
      

      【讨论】:

        【解决方案4】:

        要获取列表列表(如您的问题要求),您可以执行以下操作:

        M1 = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
        output = {}
        for l in M1:
            if l[0] in output.keys():
                output[l[0]].append(l[1:][0])
            else:
                output[l[0]] = l[1:]
        
        # Output is now a dictionary. You can stop here if you're fine with a dictionary, or continue on from here
        
        listOfLists = []
        for k, v in output.items():
            listOfLists.append([k, *v])
        

        然后是结果:

        >>> print(output)
        # {'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}
        
        >>> print(listOfLists)
        # [['a', 14, 15, 7, 16], ['b', 3, 15], ['c', 22, 1, 5]]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-24
          • 1970-01-01
          • 2021-12-29
          相关资源
          最近更新 更多