简体   繁体   中英

Concatenate a variable number of lists in Python

I have a number of lists called: index_1, index_2, index_3, ...., index_n.
What I want is to concatenate them all in a new list.

My code so far:

index_all=[]
for i in range(1,n+1):
    index_all = index_all + globals()["index_"+str(i)]   

However, I get an error:

KeyError: index_1

Any ideas as to how to solve this?

you may want to use map and filter , and the globals().items() feature:

concat_list  =  map ( lambda list_var : list_var[1] , filter ( lambda list_var  : list_var[0].startswith("list"), globals().items()))

your concat_list is the list of all items from all lists

You could try this out:

list1 = [[1,2,3],[4,5,6],[7,8,9]]

def joinAll(mulist):
     index_all=[]
     for i in mulist:
         for u in i:
             index_all.append(u)
     return index_all

print joinAll(list1)

It seems you may just have a naming error, you try to call "index_" + str(i) but your lists are named "list_" + str(i). The following line should work as long as your lists are named list_1, list_2... list_n with no breaks and your n is correct.

index_all = [globals()["list_"+str(i)] for i in range(1, n+1)]

If you want the lists to be flat you can

[item for sublist in index_all for item in sublist]

It might be easier if you can avoid using globals() as it will probably be fragile!

use list unpacking

cat_list = []
for i in range(1, n+1):
    cat_list = [ *cat_list, *globals()['index_'+str(i)] ]

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