找到每行的最大总和,找到python中最大列表计数的最大列表和行号

时间:2015-05-09 15:05:25

标签: python numpy

"[1.0, 0.5]","[0.5, 0.5, 0.5]","[0.5, 0.5]"

"[1.0, 0.0]","[0.5, 0.5, 0.5]","[0.0, 0.0]"

"[0.0, 0.0]","[0.0, 0.0, 0.0]","[0.0, 0.0]"

"[0.0, 0.0]","[1.0, 1.0, 1.0]","[0.0, 0.0]"

"[0.0, 0.0]","[0.5, 0.5, 0.5]","[1.0, 1.0]"

"[0.0, 0.0]","[0.0, 0.0, 1.0]","[0.5, 0.5]"

“[1.0,0.5]”,“[0.5,0.5,0.5]”,“[0.5,0.5]”

"[1.0, 0.0]","[0.5, 0.5, 0.5]","[0.0, 0.0]"

"[0.0, 0.0]","[0.0, 0.0, 0.0]","[0.0, 0.0]"

"[0.0, 0.0]","[1.0, 1.0, 1.0]","[0.0, 0.0]"

"[0.0, 0.0]","[0.5, 0.5, 0.5]","[1.0, 1.0]"

"[0.0, 0.0]","[0.0, 0.0, 1.0]","[0.5, 0.5]"

我有对角线列表现在我想找到每行中每个列表的总和。输出应该是这样的

1.5

1.5

0

3

1.5

1

我该怎么做?

3 个答案:

答案 0 :(得分:2)

from ast import literal_eval
with open("in.csv") as f:
    for ind, line in enumerate(f, 1):
        if line.strip():  # catch empty lines
            print(ind,max(sum(literal_eval(sub.strip('"'))) for sub in line.rstrip().split('",')))

输出:

(1, 1.5)
(2, 1.5)
(3, 0.0)
(4, 3.0)
(5, 2.0)
(6, 1.0)

使用csv模块可以让生活更轻松,因为它正确地为我们分割:

import csv
from ast import literal_eval
with open("in.csv") as f:
    reader = csv.reader(f)
    for ind, row in enumerate(reader,1):
        if row: # only needed if you have empty rows
            print(ind, max(sum(literal_eval(sub)) for sub in row))

输出:

(1, 1.5)
(2, 1.5)
(3, 0.0)
(4, 3.0)
(5, 2.0)
(6, 1.0)

ast.literal_eval

  

安全地评估表达式节点或包含Python文字或容器显示的Unicode或Latin-1编码字符串。提供的字符串或节点可能只包含以下Python文字结构:字符串,数字,元组,列表,dicts,布尔值和None。

     

这可以用于安全地评估包含来自不受信任来源的Python值的字符串,而无需自己解析值。它无法评估任意复杂的表达式,例如涉及运算符或索引。

考虑到你有一个csv文件,那么使用哪个选项是没有道理的。

如果你想要所有行的最大值,我们可以使用生成器表达式从每一行获得最大值,然后使用operator.itemgetter根据我们的元组的第二个元素得到最大值:

import csv
from ast import literal_eval
from operator import itemgetter
with open("in.csv") as f:
    reader = csv.reader(f)
    totals = ((ind, max(sum(literal_eval(sub))for sub in row))
              for ind, row in enumerate(reader, 1) if row)
    print(max(totals,key=itemgetter(1)))

输出:

 (4, 3.0) # line 4 

答案 1 :(得分:0)

从底部开始的第二行中的总和应该是2.只需将一个快速而肮脏的解决方案整合在一起:

with open('input.txt') as f:
    lines = f.readlines()

for line in lines:
    if not line.strip(): continue
    print max([sum(eval(l)) for l in line.strip('\n"').split('","')])

答案 2 :(得分:0)

<?php echo <?php my_func(); ?>
           ↑

或者,如果您的文件和输出确实有那些空行:

with open('test.csv') as file:
    for line in file:
        print(max(sum(eval(string)) for string in eval(line)))