Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove redundant square brackets in a list python [duplicate]

I am working with a list of lists longitudes and latitudes. Each inner list has an extra pair or square brackets.

For instance:

[[-87.77621462941525,-87.77676645562643,-87.77906119123564]]

I would like to remove the extra brackets and be left with:

 [-87.77621462941525,-87.77676645562643,-87.77906119123564] 

Thanks

like image 751
mwaks Avatar asked Mar 06 '17 02:03

mwaks


People also ask

How do I remove double square brackets from a list in Python?

In Python, we use the replace() function to replace some portion of a string with another string. We can use this function to remove parentheses from string in Python by replacing their occurrences with an empty character.

Why are there two square brackets in Python?

You can either use a single bracket or a double bracket. The single bracket will output a Pandas Series, while a double bracket will output a Pandas DataFrame. Square brackets can also be used to access observations (rows) from a DataFrame.

How do you remove brackets from text in Python?

In python, we can remove brackets with the help of regular expressions. # pattern is the special RE expression for finding the brackets.


2 Answers

this is nested list object, you can access the inner list with index.

In [1]: l = [[-87.77621462941525,-87.77676645562643,-87.77906119123564,]]

In [2]: l[0]
Out[2]: [-87.77621462941525, -87.77676645562643, -87.77906119123564]
like image 61
宏杰李 Avatar answered Sep 30 '22 09:09

宏杰李


List Indexing

You can simply use list indexing.

my_lists = [[-87.77621462941525,-87.77676645562643,-87.77906119123564,]]
my_list  = my_lists[0]

next

Another way of doing this is using next which takes an iterable as an argument. It will raise a StopIteration in the case of the iterable being empty. You can prevent this by adding a default value as a second argument.

my_list = next(iter(my_lists))

Or

my_list = next(iter(my_list), [])  # Using [] here but the second argument can be anything, really

Obviously this second option might be a bit of overkill for your case but I find it a useful one-liner in many cases. For example:

next_element = next(iter(list_of_unknown_size), None)

Versus

next_element = list_of_unknown_size[0] if list_of_unknown_size else None
like image 32
aydow Avatar answered Sep 30 '22 09:09

aydow