简体   繁体   中英

Remove all elements except string from list

I have a list which looks like this [[{a:7},"1",{x:0.25},"2"],[{y:0.25,x:1.5},"4"],[{y:-0.75},"3"]] and i want to remove everything that isn't a string from the list while still keeping the "shape" of the list so the output should look like this [["1", "2"], ["4"], ["3"]] . How can i do this?

To create new list with required values, you can use list comprehension:

given = [[{a: 7}, "1", {x: 0.25}, "2"], [{y: 0.25, x: 1.5}, "4"], [{y: -0.75}, "3"]]
new_data = [[e for e in inner if isinstance(e, str)] for inner in given]

This means: "create new list of lists, where inner items are only string values".

If you need to modify given list inplace, the following should do:

given = [[{a: 7}, "1", {x: 0.25}, "2"], [{y: 0.25, x: 1.5}, "4"], [{y: -0.75}, "3"]]
for i, inner in enumerate(given):
    given[i] = [e for e in inner if isinstance(e, str)]

Using pop or del in such context is not advisable, because a) it changes list length during iteration (and is bug prone), and b) it is less efficient.

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