【问题标题】:Convert list of list into one big list python将列表列表转换为一个大列表python
【发布时间】:2016-06-03 19:38:25
【问题描述】:

我有一个类似的列表:

list1 = [1  2  1 ... 1  399]

还有一个:

list2 = [5 4  3  4  2 0]

list1有来自0 to 399的数字,有重复,长度为5000list2的长度为400,每个list2元素的索引代表list1中元素的编号,这就是它具有400 长度的原因。 我想返回一个长度为5000(与list1相同)的列表,并检查每个元素,如果list1的第一个元素是1,我想将list2中1的索引添加到新列表中,这在这种情况下是 4, 所以新列表应该是

new_list = [ 4 , ...]

以此类推,直到它出现

我试过了,但没有用:

labels=labels.tolist()
labels2=labels2.tolist()
new=list()

for i in range(len(labels1)):
     for item,index in enumerate(labels2):

         # print(item)
          if labels1[i] == index :
             # print (str(labels2[i]).index)
              new.append(item)

print(new)

【问题讨论】:

  • 请为给定的两个输入填写所需的结果new_list

标签: python list enumeration


【解决方案1】:

您需要根据 list1 中的值对 list1 的每个值编制索引。您可以从 for 循环构建它:

new_list = []
for k in list1:
  new_list.append(list2[k]) #lookup the value in list2 at the index given by list1

这更用 Python 方式用列表推导式表达:

new_list = [list2[k] for k in list1]

【讨论】:

    【解决方案2】:

    列表理解。

    n_l = [list2[i] for i in list1]
    

    【讨论】:

      【解决方案3】:

      使用 numpy 模块是一种非常快速有效的解决方案:

      In [46]: a1[l2]
      Out[46]: array([4, 3, 1, 1, 1, 2])
      

      设置:

      import numpy as np
      
      l1 = [1,2,1,1,3,4,5,6,7,8,5,7,8,9]
      l2 = [5,4,3,2,0,1]
      a1 = np.array(l1)
      

      【讨论】:

      • 这是相反的。他想要 l2 的值对应于 l1 给出的每个索引,所以它将是:a2[l1]
      【解决方案4】:

      从list2项的索引到itedelf建立一个字典,然后通过字典传递list1项:

      new_dict={}
      for i,v in enumerate(list2):
          new_dict[i]=v
      
      new_list=[]
      for i in list1:
          new_list.append(new_dict[i])
      
      print new_list
      

      【讨论】:

      • 你不应该追加new_dict[i]吗?
      猜你喜欢
      • 2016-05-27
      • 2012-09-29
      • 2016-07-05
      • 2018-01-17
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多