Skip to main content
 首页 » 编程设计

python之python中的文本文件

2024年11月24日7zfyouxi

我在 python jupyter notebook 中有一个文本文件。问题是“计算大于 0.1 的数字”。我不知道如何为此编写代码。文本文件有名称和整数。我想我可以为此创建两个列表,但不确定如何获取大于 .1 的数字的输出。

这是我到目前为止编写的代码。

def ans9(file): 
    infile = open(file) 
    contents = infile.read().split() 
    infile.close() 

请您参考如下方法:

如果您只需要对它们进行计数,那么这样的方法就可以了:

def ans9(file): 
    with open(file, 'r') as infile: 
        count = 0 
        for line in infile: 
            if float(line.split('\t')[1]) >  0.1: 
                count += 1 
 
    return count 

如果您想要数据的拆分表示:

def ans9(file): 
    with open(file, 'r') as infile: 
        items = [] 
        for line in infile: 
            item = line.split('\t') 
            if float(item[1]) >  0.1: 
                items.append(item) 
 
    return items 

会返回一个看起来像 [["a", "0.22"], ["b", "0.11"]] 的列表,您可以很容易地遍历它。