简体   繁体   中英

Combine strings and list of strings to one big list

I have variables of just strings or list of strings like so (but a lot more than just in three my code):

a = 'apples'
b = 'pears'
c = ['grapes', 'bananas', 'kiwis']

Is there an easy way to combine them to get a one big list ['apples', 'pears', 'grapes', 'bananas', 'kiwis'] ? I tried a + b + c but I get TypeError: can only concatenate str (not "list") to str . There is no order to where strings/lists appear. This must be an incredibly easy and silly question but I couldn't find an answer - apologies if duplicate...

Edit:

Clarification due to above example being pointed out as too trivial: I have a big list of variables, some of which are just strings and some of which are list of strings. They are not ordered and I was wondering if there was an easy way to combine them without manually seeing which are strings and which are lists and treat the variables separately in my code. If it is not possible that is an answer too.

Yes, you can create a new list in which you "unpack" the lists, and add the other string elements, like:

new_list = [a, b, ]

If you want to add the elements of the list, you thus need to prepend this with an asterisk.

If it is not known in advance what the lists are, we can inspect that, and thus unpack these, for example with:

from itertools import chain

new_list = list(chain.from_iterable(
    x if isinstance(x, list) else (x,) for x in [a, b, c])
)

You can try this way

total = []
for i in [a, b, c,...]:
    if isinstance(i, list):
        total += i
    else:
        total.append(i)
for x in [a,b]:
    c.append(x)
for obj in list_of_strings_and_lists
  if isinstance(obj, basestring):
    new_list.append(obj)
  else: # it's a list
    new_list += obj

I've not tested this, but you basically just need to use isinstance to either append the string or add (concatenate) the lists.

In order to create such a list, you need to use the extend method. But if you pass a string it will expend the chars of the string to the list, so you need a convert function in order to omit it. This function checks if the variable is a list, if so then it returns it, otherwise, if it is a string it creates a list of one element (the string).

a = 'apples'
b = 'pears'
c = ['grapes', 'bananas', 'kiwis']
def convert(a):
    if type(a)==list:
        return a
    elif type(a)==str:
        return [a]
d=[]
for i in [a,b,c]:
    d.extend(convert(i))
print(d)

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