[英]Save a nested list into new smaller lists with python
我有一個列表(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)
我希望輸出如下:
list1=[39.435138344488145, 22.73229454094485]
list2=[39.43684333469196, 22.73215634579526]
list3= [39.43681019007974, 22.731609175156223]
etc
試試這個 -
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]
這應該會給你你想要的輸出! :)
我想這就是你想要的:
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")
據說你最好只為大多數用例做列表索引。 (通常不建議使用exec
和eval
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.