I needed to pass%% of type:
0.4350 0.8798 0.0099 1
for a string
[0.4350, 0.8798, 0.0099, 1]
with a simple list
. How can I do this?
I needed to pass%% of type:
0.4350 0.8798 0.0099 1
for a string
[0.4350, 0.8798, 0.0099, 1]
with a simple list
. How can I do this?
If you have a string with "0.4350 0.8798 0.0099 1", you need to do two operations: separate the elements where there is white space, and for each separate element, which will be a string, transform it into a float number.
The first operation will always be done by the "split" method of strings in Python. By default this method still has the advantage of considering any number of whitespace (and other spacing characters such as newline, tabs, etc ...) as a single space:
>>> a = "0.4350 0.8798 0.0099 1"
>>> b = a.split()
>>> b
['0.4350', '0.8798', '0.0099', '1']
For those of you in the first steps in Python, the easiest way to understand the second operation is to create a blank list, and for
than for each element in b
add its converted value to float in new list:
>>> c = []
>>> for elemento in b:
... c.append(float(elemento))
...
>>> c
[0.435, 0.8798, 0.0099, 1.0]
But as people become more comfortable with Python, the ideal thing to do is to use a list comprehension - it's an expression of Pythonq sitnaxe that lets you create a list from an arbitrary sequence using% on the same line - as an expression. Your entire problem would be solved like this:
c = [float(elemento) for elemento in "0.4350 0.8798 0.0099 1".split()]
(The contents of c will be the same as in the previous example).
What this form does: first you execute the expression that "for" will use, after the "in" - this is your initial string (which can be in a variable, of course), with the for
method. Then the split
is executed, and for each part of the sequence returned by the split, the expression before for
, for
is executed, and its result becomes part of the final list assigned to variable float(elemento)
.
c
creates a generator, which must be transformed into a list:
c = list(map(float, "0.4350 0.8798 0.0099 1".split()))
The version with list-comprehension is generally more expressive and easier to "think" than the approach to functional syntax - but does not prevent personal taste from using map
. >
I'm not a developer python , but I managed to solve it this way :
Code :
str = '0.4350 0.8798 0.0099 1';
val = filter(None, str.split(' '));
print val
Output :
['0.4350', '0.8798', '0.0099', '1']
def noEmpty(x):
return x != ""
str = '0.4350 0.8798 0.0099 1';
print (list(filter(noEmpty, str.split(' '))));