简体   繁体   中英

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. 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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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