忽略列表中的元素直到某个索引

时间:2016-08-04 22:46:11

标签: python list

我通过从具有两列的文本文件中读取来创建两个列表,这两列始终具有相同的布局,但列的长度不同。

def read_columns(x,y,filename,rw):
            print(filename)
            if(not os.path.isfile(filename)):
                sys.exit(filename + " does not exist")

            file = open(filename,rw)
            left_column = True
            for line in file:
                # print(line)
                if ("X" not in line and line is not ""):
                    s = line.split()
                    for floats in s:
                        if left_column:
                            left_column = False
                            x.append(float(floats))
                        else:
                            y.append(float(floats))
                            left_column = True

然后我想在Y列表中找到最小值

def find_minforce(y):                
            min_force = min(y)

            return min_force

然而,最小y值的对应x值应该高于某个值。像忽略所有y值,相应的x值低于0.01。有什么建议吗?

例如

x y
0 -8
1 -9
2 -4
2.5 -6
2.71 -3

如果我想忽略所有x< 2

,我应该得到minimum_y = -6

1 个答案:

答案 0 :(得分:0)

除了您尝试做的事情之外,您的代码中还有一些问题。我试图解决错误并解释我在做什么。

with open(filename) as f:
    data = [point for point in 
            (Point(*(float(_) for _ in line.split())
             for line in f if line.strip() and 'X' not in line)
            if point.x > 2
            ]

# could be compressed into one line, but that's not very readable.
with open(filename) as f:
    data = [point for point in (Point(*(float(_) for _ in line.split()) for line in f if line.strip() and 'X' not in line) if point.x > 2]

请注意,如果我不担心该文件存在,我可能会这样做:

{{1}}

该方法使用列表推导,生成器理解和参数解包。他们是非常强大的技术。