我有一个嵌套列表(4个级别),并希望将每个列表项(第一级)作为新列表。我知道如何打印这个:
mynestedlist = [[([6, "x1a", "y1a"], [8, "x1b", "y1b"]), ([9, "x2a", "y2b"], [4, "x2b", "y2b"])],
[([6, "x1a", "y1a"], [9, "x2a", "y2b"]), ([8, "x1b", "y1b"], [4, "x2b", "y2b"])],
[([6, "x1a", "y1a"], [4, "x2b", "y2b"]), ([9, "x2a", "y2b"], [8, "x1b", "y1b"])]]
for i in range(0,len(mynestedlist)):
print(i)
print(mynestedlist[i])
但我想把每个项目作为一个新列表。我无法做到这一点,因为我不知道如何自动更改列表名称,因此我不会在每个循环中覆盖我的列表。 我试过像:
for i in range(0,len(mynestedlist)):
"list"+str(i) = [mynestedlist[i]]
但这不起作用(显然,我猜)。可能是一个简单的问题,但我无法解决,请帮忙吗?
答案 0 :(得分:0)
您可以在这里使用Dictionary
,使用"list + str(i)"
键的字典和值是所需的列表:
myDic = {}
for key,value in enumerate(mynestedlist,1):
myDic["list"+str(key)] = value
结果:
{'list3': [([6, 'x1a', 'y1a'], [4, 'x2b', 'y2b']), ([9, 'x2a', 'y2b'], [8, 'x1b', 'y1b'])], 'list1': [([6, 'x1a', 'y1a'], [8, 'x1b', 'y1b']), ([9, 'x2a', 'y2b'], [4, 'x2b', 'y2b'])], 'list2': [([6, 'x1a', 'y1a'], [9, 'x2a', 'y2b']), ([8, 'x1b', 'y1b'], [4, 'x2b', 'y2b'])]
有关字典的更多信息,请访问:
答案 1 :(得分:0)
如果我正确理解了这个问题,你想在嵌套列表中找出最后一个嵌套及其索引。我能想到的解决方案虽然值得学习,但并不简单:
def lastnest(nest, level=0, c=0):
level += 2
counter = 0
for j in nest:
if any([type(x) == list or type(x) == tuple for x in j]):
for i in j:
c += 1
if type(i) is list or type(i) is tuple:
lastnest(i, level=level, c=c)
else:
counter += 1
print level, (c-1)%len(j), counter, j
lastnest(mynestedlist)
这应该打印出level,nest id和nest item索引以及列表本身,但它确实假设所有最后的嵌套都是相同的len()