简体   繁体   中英

python: how to append multiple lists to one

I have a list that should contain all my other lists. Currently I append every list separately but that just looks pretty ugly..

looplist = []  # initiate an empty list that contains all date from the other lists 
[...]
looplist.append(internallist1)
[...]
looplist.append(internallist10)

the internallists are all getting initialized and filled in a for loop

You can simply use + to merge them.

You may check for more info.

If you want to have list of lists, check this topic.

listOne.extend(anotherList)

this could help you: https://docs.python.org/3/tutorial/datastructures.html

you can also do listOne+=anotherList and this is less expensive, as it doesn`t involve a function call like extend

To answer what you are asking, Just initialize looplist with your 10 lists.

looplist = [internallist1,
            internallist2,
            internallist3] #Note: internallist3,] is also valid, python allows trailing comma. Nifty!

However, your 10 lists really shouldn't be separately named lists in the first place if this is your real use case. Just use looplist[0] through looplist[9] instead from the get go.

The zip method could work for you as you stated your output should:

look something like [ [list1], [list2], ... , [list n] ]

in your case the code would be similar to

looplist = list(zip(internallist1,[...], internallist10))

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