Covert input into list elements in python -
i have input in python looks this:
20.1 25.9 31.2 33.2 31.2 25.5 28.1 23.2 stop
it sequence of floating point numbers, each on separate line. wish iterate on them or convert them list iterate, can't find right way it. far have tried this:
list = [float(n) n in input().split('\n')]
but returns me first value. wish convert values list , keep integrity of them.
the input function reads single line. need call multiple times , check 'stop'.
import sys mylist = [] line in sys.stdin: if line.startswith('stop'): break else: mylist.append(float(line)) print(mylist)
itertools.dropwhile
can of work you. give function returns false value when iteration should stop, plus sequence, , can work in list comprension.
import sys import itertools def not_stop_condition(line): """return true unless line 'stop' seen""" return not line.startswith('stop') mylist = [float(line) line in itertools.takewhile( not_stop_condition, sys.stdin)] print(mylist)
small functions implement simple expression not_stop_condition
can placed in-line in lambda
. lambda
anonymous function - called number of parameters , returns whatever expression evaluates to.
import sys import itertools mylist = [float(line) line in itertools.takewhile( lambda line: not line.startswith('stop'), sys.stdin)] print(mylist)
Comments
Post a Comment