检查其他列表中的值是否小于x

时间:2019-11-19 17:04:52

标签: python

我不能使用csv模块,所以我要打开这样的csv文件:

def readdata(filename):
    res = []
    tmp = []
    with open(filename) as f:
        l = f.readlines()
        for i in range(len(l)):
            tmp.append(l[i].strip().split(';'))

    for i in range(len(tmp)):
        for j in range(len(tmp[i])):
            if j > len(res)-1:
                res.append([])
            res[j].append(tmp[i][j])
    return res


res_count_file = "count.csv"

data_count_file = readdata(res_count_file)


此csv文件包含以下内容:

ro1;ro2;ro3
5;3;5
8;2;4
6;2;666
15;6;3
2;1;
6;9;7

现在,我的函数将其读取并将其分为3个列表:

[['ro1', '5', '8', '6', '15', '2', '6'], ['ro2', '3', '2', '2', '6', '1', '9'], ['ro3', '5', '4', '666', '3', '', '7']]

我需要检查一行的值是否小于x(假设x = 10),如果不是,则:score + = 1 例如:

5;3;5  //none of them are greater then x so score += 1
8;2;4  //none of them are greater then x so score += 1
15;6;3 // 15 is greater then x so nothing happens
2;1;   // none of them are greater then x so score += 1 even if there is nothing in ro3, I need to convert the empty string "''" into 0 

现在,我尝试在for循环中调用此函数,以检查数字是否小于X,如果返回true,则增加分数,但是我不知道如何检查R01中的所有3个数字R02 R03如示例所示。

def apprenant_fiable(data,index_of,i):


    if data[index_of][i] == "":

        return True

    elif int(data[index_of][i]) <= 10 :
            #print(data[index_of][i],"***PASS")
        return True
    else :
            #print(data[index_of][i],"***FAIL")
        return False

目标是输出总分。

4 个答案:

答案 0 :(得分:1)

您可以在生成器上使用sum

lst = [['ro1', '5', '8', '6', '15', '2', '6'], ['ro2', '3', '2', '2', '6', '1', '9'], ['ro3', '5', '4', '666', '3', '0', '7']]

val = 10
score = sum(all(y <= val for y in x) for x in zip(*[map(int, x[1:]) for x in lst]))

# 4

请注意,我已将列表中的空字符串替换为'0',在形成列表时需要处理该空字符串。


val = 10
for x in zip(*[map(int, x[1:]) for x in lst]):
    if all(y <= val for y in x):
        print(x)

这现在将打印出所有有助于添加score的行。

答案 1 :(得分:0)

像这样?其中list_of_3_lists是您读取输入文件的结果

total = 0
for l in list_of_3_lists:
    if all([int(t) > 10 for t in l[1:]]):
        total +=1
print(total)

答案 2 :(得分:0)

您的问题出在您的职能部门之首:

def apprenant_fiable(data, index_of, i):
                           ########

您专门告诉您的函数仅查看三个列表之一。摆脱这个。在函数内部,您将在某处拥有

    for value, index in enumerate(data)

在确定返回值之前,您需要检查所有值。 如果您不知道如何执行此操作,那么有很多地方可以教您如何在馆藏中寻找某种品质的物品。

答案 3 :(得分:0)

您可以使用pandas模块轻松完成此操作

import pandas as pd

# read the csv
df = pd.read_csv('input.csv', delimiter=';').fillna(0)
# leave only the rows with sum greater then 10
print(df[df.sum(axis=1) > 10].shape[0])