我有一个列表(此列表),我将其分成较小的列表(嵌套),我想获取嵌套列表的每个索引,并将其保存在其他列表,数组等中
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
答案 0 :(得分:0)
尝试一下-
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]
这应该为您提供所需的输出! :)
答案 1 :(得分:0)
我想这就是你想要的:
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
。