将列表的列表转换为一个大列表python
Convert list of list into one big list python
我有一个列表:
list1 = [1 2 1 ... 1 399]
还有一个:
list2 = [5 4 3 4 2 0]
list1 有来自 0 to 399
的数字,重复且长度为 5000
,list2
的长度为 400
,每个 list2
的索引elements 表示 list1
中元素的数量,这就是为什么它具有 400
长度。
我想 return 一个长度为 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)
您需要根据 list1 中的值,为 list1 的每个值索引到 list2。您可以从 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]
列表理解。
n_l = [list2[i] for i in list1]
非常快速和有效的解决方案之一是使用 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)
从list2项的索引到itedelf项构建字典,然后通过字典传递list 1项:
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
我有一个列表:
list1 = [1 2 1 ... 1 399]
还有一个:
list2 = [5 4 3 4 2 0]
list1 有来自 0 to 399
的数字,重复且长度为 5000
,list2
的长度为 400
,每个 list2
的索引elements 表示 list1
中元素的数量,这就是为什么它具有 400
长度。
我想 return 一个长度为 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)
您需要根据 list1 中的值,为 list1 的每个值索引到 list2。您可以从 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]
列表理解。
n_l = [list2[i] for i in list1]
非常快速和有效的解决方案之一是使用 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)
从list2项的索引到itedelf项构建字典,然后通过字典传递list 1项:
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