简体   繁体   中英

python extend or append a list when appropriate

Is there a simple way to append a list if X is a string, but extend it if X is a list? I know I can simply test if an object is a string or list, but I was wondering if there is a quicker way than this?

mylist.extend( [x] if type(x) == str else x )

or maybe the opposite would be safer if you want to catch things other than strings too:

mylist.extend( x if type(x) == list else [x] )

I do not think so. extend takes any iterable as input, and strings as well as lists are iterables in python.

buffer = ["str", [1, 2, 3], 4]
myList = []

for x in buffer:
    if isinstance(x, str):
        myList.append(x)
    elif isinstance(x, list):
        myList.extend(x)
    else:
        print("{} is neither string nor list".format(x))

A better way would be using try-except instead of isinstance()

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