[英]Fill a list in python with values from a smaller list by indexes contained in another list with the same size?
I have a list full of indexes named g_index, I have another list of the same size,named fill_list, full of values.我有一个名为 g_index 的索引列表,我有另一个相同大小的列表,名为 fill_list,充满了值。 I also have another list, P1, that is longer than g_index and fill_list.
我还有另一个列表 P1,它比 g_index 和 fill_list 长。 I want to create a new list of size, P1, that has the value of fill_list in the indexes of g_index, with the rest of the values being therefore, None.
我想创建一个大小为 P1 的新列表,它在 g_index 的索引中具有 fill_list 的值,因此其余的值是 None。 Note that the items in fill_list will fill the indexes in g index in a sequential order.
请注意,fill_list 中的项将按顺序填充 g index 中的索引。 This means that the first item of fill_list will go on index 3 of the new list ( I call it finaList in the code) and so on and so forth.
这意味着 fill_list 的第一项将在新列表的索引 3 上(我在代码中称其为 finaList),依此类推。 The size of the list created should be the size of P1, with the values of fill_list in indexes denoted by g_index.
创建的列表的大小应该是P1的大小,索引中fill_list的值用g_index表示。 Here is what I have:
这是我所拥有的:
g_index=[3,6,2,83,7,100,5,1]
fill_list=["lk",3,6,9,"gh",4,7,34]
finalList=[]
for index in range(len(P1)):
for j in range(len(g_index)):
if index== g_index[j]:
finalList.append(fill_list)
print finalist
In my code, the final list just keeps appending itself with values, which is not what I am looking for.在我的代码中,最终列表只是不断附加值,这不是我想要的。
What about something like this:这样的事情怎么样:
final_list = []
for i in range(len(P1)):
if i in g_index:
final_list.append(fill_list)
else:
final_list.append(None)
In the above example, whatever
could be the whole final_list, or an item from fill_list.在上面的例子中,
whatever
是整个 final_list 还是 fill_list 中的一个项目。
You can create a list with None (or anything else) and then map the values like this:您可以使用 None (或其他任何内容)创建一个列表,然后像这样映射值:
g_index=[3,6,2,83,7,100,5,1]
fill_list=["lk",3,6,9,"gh",4,7,34]
p1 = [None] * (max(g_index) + 1)
for k, v in enumerate(g_index):
p1[v] = fill_list[k]
print(p1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.