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
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.
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.
In python, we can remove brackets with the help of regular expressions. # pattern is the special RE expression for finding the brackets.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With