I'm having a problem with square brackets in Python. I wrote a code that produces the following output:
[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
But I would like to perform some calculations with that, but the the square brackets won't let me.
How can I remove the brackets? I saw some examples to do that but I could not apply them to this case.
Given
d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
and your specific question: How can I remove the brackets?
Using list comprehension :
new_d = [i[0] for i in d]
will give you this
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
then you can access individual items with the appropriate index, e.g., new_d[0]
will give you 180.0
etc which you can then use for math.
If you are going to have a collection of data, you will have some sort of bracket or parenthesis.
Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.
I would use itertools.chain
- this will also cater for > 1 element in each sublist:
from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))
>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!
list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]
Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:
flattened = [val for sublist in list_of_lists for val in sublist]
is equivalent to:
flattened = []
for sublist in list_of_lists:
for val in sublist:
flattened.append(val)
The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!
If you have multiple items in a sublist the list comp will even flatten that. ie
>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened = [val for sublist in list_of_lists for val in sublist]
>>> flattened
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]
Source: Stackoverflow.com