Flatten a list of strings which contains sublists

2024/10/12 8:24:02

I have a list of strings which contains a sublist os strings:

ids = [u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', [u'spotify:track:6oRbm1KOqskLTFc1rvGi5F',
u'spotify:track:045sp2JToyTaaKyXkGejPy']]

I tried to flatten it with:

[item for item in ids for item in sublist]

and

chain = itertools.chain(ids)

but these solutions split the strings...

how do I flatten the original list into

[u'spotify:track:3ftnDaaL02tMeOZBunIwls', u'spotify:track:4CKjTXDDWIrS0cwSA9scgk', u'spotify:track:6oRbm1KOqskLTFc1rvGi5F',u'spotify:track:045sp2JToyTaaKyXkGejPy']

?

Answer

You could use a simple loop with an isinstance check.

out = []
for i in ids:if isinstance(i, list):out.extend(i)else:out.append(i)print(out)  

Output:

['spotify:track:3ftnDaaL02tMeOZBunIwls','spotify:track:4CKjTXDDWIrS0cwSA9scgk','spotify:track:6oRbm1KOqskLTFc1rvGi5F','spotify:track:045sp2JToyTaaKyXkGejPy'] 

You could also use itertools.chain, but with an extra layer of preprocessing:

from itertools import chainout = list(chain.from_iterable([i if isinstance(i, list) else [i] for i in ids]))
print(out)    

With the same output.

https://en.xdnf.cn/q/118220.html

Related Q&A

Portscanner producing possible error

I have written a simple portscanner in python. I have already asked something about it, you can find the code here.I corrected the code and now am able to create a connection to e.g. stackoverflow.netB…

Import error on first-party library with dev_appserver.py

On Ubuntu 16.04, am suddenly getting import errors from the local GAE development server. The local dev server starts up, including the admin interface, but app no longer loads.Native python imports o…

Split dictionary based on values

I have a dictionary:data = {cluster: A, node: B, mount: [C, D, E]}Im trying to split the dictionary data into number of dictionaries based on values in key mount.I tried using:for value in data.items()…

Using defaultdict to parse multi delimiter file

I need to parse a file which has contents that look like this:20 31022550 G 1396 =:0:0.00:0.00:0.00:0:0:0.00:0.00:0.00:0:0.00:0.00:0.00 A:2:60.00:33.00:37.00:2:0:0.02:0.02:40.00:2:0.98:126.00…

Iterating in DataFrame and writing down the index of the values where a condition is met

I have a data made of 20 rows and 2500 columns. Each column is a unique product and rows are time series, results of measurements. Therefore each product is measured 20 times and there are 2500 product…

Access denied to ClearDB database using Python/Django on Heroku

Im trying to build a webapp on Heroku using Python/Django, and I just followed the tutorial to set up a Django project and push it to Heroku. However, I can never even get to the normal Django "I…

Replacing a line in a file based on a keyword search, by line from another file

Here is my file1: agadfadsdffasdfElement 1, 0, 0, 0PcomElement 2Here is my file2: PBARElement 1, 100, 200, 300, 400Element 2Continue...I want to search with a keyword, "Element 1" in file1,…

How to check for pop up alert using selenium in python

What I want is to continue with the next iteration if there is a pop up message in the webpage being scrapped. That is if there is any pop up message, I want to accept that message and go to the next i…

Rally host is non-existent or unreachable via pyral

I am trying to call rally server simply using below: rally = Rally(server, user, password, workspace=workspace, project=project)But it is giving below error:Traceback (most recent call last):File "…

Query tangled array in Pymongo

I am trying to query a very tangled collection. The schema:{tags: {variables: [{value: 3x9, var_name: s},{value: 12:00AM, var_name: x},{value: goog, var_name: y}]},url: https://www.google.com}]The Quer…