Python 检查不同列表中的值是否小于x
我无法使用csv模块,因此我正在打开如下csv文件:Python 检查不同列表中的值是否小于x,python,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)):
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 R02 R03中的所有3个数字,如示例所示
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
def附件(数据,索引,i):
如果数据[index_of][i]==“”:
返回真值
elif int(data[index_of][i])类似的东西?其中,list_of_3_list是读取输入文件的结果
total = 0
for l in list_of_3_lists:
if all([int(t) > 10 for t in l[1:]]):
total +=1
print(total)
您可以在生成器上使用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
现在,这将打印出所有有助于添加分数的行
您的问题在函数的头部:
def apprenant_fiable(data, index_of, i):
########
您特别告诉函数只查看三个列表中的一个。把这个扔掉。在函数中,您将在某个地方
for value, index in enumerate(data)
在决定返回什么之前,需要检查所有值。
如果您不知道如何做到这一点,有很多地方可以教您如何在收藏中寻找某种质量的产品。您可以使用熊猫
模块轻松做到这一点
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])
最终输出是什么?总分?是的,对不起。我需要所有这些的最终分数不能用熊猫?这需要两行代码…奇怪的是,为什么不能使用csv模块?如果全部([t>10表示l[1:]中的t):^SyntaxError:无效syntax@FelixDumitrascu:if all([t>10表示l[1:]中的t):
;顺便说一句,在进行比较之前,您需要将其更改为整数。这非常有效,但我无法确定如何将其应用到我的程序中。我需要找出生成分数+1的哪一行值,以便将其应用到smth。您能给我一点时间吗?或者stackoverflow上不可能有PM?@FelixDumitrascu,没有PMs。请参见上面您想要的答案(刚刚编辑)。:)
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])