2017-04-07 58 views
0

列表元素我在蟒,看起来像这样的输入:隐蔽输入到蟒

20.1 
25.9 
31.2 
33.2 
31.2 
25.5 
28.1 
23.2 
stop 

它是浮点数字的序列,每个在单独的行。我希望遍历它们或将它们转换为列表来迭代,但我找不到正确的方法来完成它。 到目前为止,我已经试过这样:

list = [float(n) for n in input().split('\n')] 

但它只返回我的第一个值。 我希望将所有值转换为列表并保持其完整性。

回答

0

输入函数只读取一行。您需要多次调用并检查“停止”。

import sys 

mylist = [] 
for line in sys.stdin: 
    if line.startswith('stop'): 
     break 
    else: 
     mylist.append(float(line)) 

print(mylist) 

itertools.dropwhile可以为你做一些工作。给它一个函数,当迭代应该停止时返回一个False值,加上一个序列,并且你可以在列表扩展中完成工作。

import sys 
import itertools 

def not_stop_condition(line): 
    """Return True unless a line with 'stop' is seen""" 
    return not line.startswith('stop') 

mylist = [float(line) for line in itertools.takewhile(
    not_stop_condition, sys.stdin)] 

print(mylist) 

,仅仅实现像not_stop_condition简单表达的小的功能可以被放置在线路中一个lambda。 A lambda只是一个匿名函数 - 用任意数量的参数调用并返回表达式计算的任何值。

import sys 
import itertools 

mylist = [float(line) for line in itertools.takewhile(
    lambda line: not line.startswith('stop'), sys.stdin)] 
print(mylist) 
+0

使用其他空格(例如'''')来分隔它们的'input's会不会更容易? –

+0

@Chris_Rands - 我们不知道输入来自哪里。改变来源可能是不可能的。将行分隔的数据传送到程序中是正常的,如果输入变大,则它是更好的方法。考虑一个拥有1000万浮点数的数据集。 – tdelaney

+0

谢谢,它真的有效,** lambda **函数是什么? – Leonor