简体   繁体   English

Python:为所有嵌套列表项创建新列表(级别1)

[英]Python: make new lists for all nested list items (level 1)

I have a nested list (4 levels) and want to give out each list item (first level) as a new list. 我有一个嵌套的列表(4个级别),并且希望将每个列表项(第一个级别)作为新列表给出。 I know how to print this: 我知道如何打印此:

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])

But I want to give each item out as a new list. 但我想将每个项目都列为新清单。 I can't do this because I do not know how to automatically change the name of the list so I don't overwrite my list in each loop. 我无法执行此操作,因为我不知道如何自动更改列表的名称,因此我不会在每个循环中覆盖列表。 I tried something like: 我尝试了类似的东西:

for i in range(0,len(mynestedlist)):
    "list"+str(i) = [mynestedlist[i]]

but this doesn't work (obviously, I guess). 但这是行不通的(显然,我想)。 Probably an easy question but I can't solve it, please help? 可能是一个简单的问题,但我无法解决,请帮助?

You can use Dictionary here , dictionary with "list + str(i)" key and value is desired list : 您可以在此处使用Dictionary ,使用带有"list + str(i)"键的字典,需要的值是list:

myDic = {}
for key,value in enumerate(mynestedlist,1):
    myDic["list"+str(key)] = value

Result: 结果:

{'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'])]

For more information about dictionary visit here: 有关字典的更多信息,请访问此处:

Python Dictionary Python字典

if I understand the question correctly, you would like to identify the last nest and its index in your nested list. 如果我对问题的理解正确,则希望在嵌套列表中标识出最后一个嵌套及其索引。 the solution that I can think of is not straight forward though worth learning about: 虽然值得学习,但我能想到的解决方案并非直截了当:

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)

this should print out the level, nest id and nest item index as well as the list itself, but it does assume that all the last nests will be of the same len() 这应该打印出级别,嵌套ID和嵌套项索引以及列表本身,但是它确实假定所有最后的嵌套都将具有相同的len()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM