[英]Save a nested list into new smaller lists with python
I have a list(thislist), i split it in smaller lists(nested) and i want to take each index of the nested list and save it in different list,array etc 我有一个列表(thislist),我将它拆分为较小的列表(嵌套),我想采取嵌套列表的每个索引,并将其保存在不同的列表,数组等
thislist = [39.435138344488145, 22.73229454094485, 39.43684333469196, 22.73215634579526, 39.43681019007974, 22.731609175156223, 39.43507007579199, 22.731759378861057, 39.43511979394629, 22.732236812065707, 39.435138344488145, 22.73229454094485]
n = 2
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
x = list(divide_chunks(thislist, n))
print(x)
I expect the output to be like: 我希望输出如下:
list1=[39.435138344488145, 22.73229454094485]
list2=[39.43684333469196, 22.73215634579526]
list3= [39.43681019007974, 22.731609175156223]
etc
Try this out- 试试这个 -
chunks = [thislist[x:x+2] for x in range(0, len(thislist), 2)]
list_dict = {i: chunks[i] for i in range(0, len(chunks))}
g = globals()
for i in range(0, len(chunks)):
g['list{0}'.format(i)] = list_dict[i]
This should give you your desired output! 这应该会给你你想要的输出! :) :)
I think this is what you want: 我想这就是你想要的:
thislist = [39.435138344488145, 22.73229454094485, 39.43684333469196, 22.73215634579526, 39.43681019007974, 22.731609175156223, 39.43507007579199, 22.731759378861057, 39.43511979394629, 22.732236812065707, 39.435138344488145, 22.73229454094485]
n = 2
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
for index, x in enumerate(divide_chunks(thislist, n)):
exec("list{} = x".format(index + 1))
try:
print(list1)
except NameError:
print("Not a valid list")
That being said you are better off just doing list indexing for most use cases. 据说你最好只为大多数用例做列表索引。 (Using exec
and eval
is usually not recommended). (通常不建议使用exec
和eval
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.