简体   繁体   English

如何在python中将sum用于列表中的特定值?

[英]How can I use sum in python for specific values in a list?

I have a text file that looks like this; 我有一个看起来像这样的文本文件; the values are tab separated: 值以制表符分隔:

diamond orange pear loc1  .  +    0.0  0.0  0.0  0.0  1.0 1.2  3.4 
diamond orange pear loc2  .  +    1.0  0.0  0.0  0.0  1.0 1.2  2.3
diamond orange pear loc3  .  +    2.0  0.0  3.0  0.0  0.0 0.0  1.4  
# ......

For each line in the file I want to make a ratio of the sum of the first 3 values divided by the sum of the last 4 values. 对于文件中的每一行,我想将前3个值的总和除以后4个值的总和之比。 The output would look like: 输出如下所示:

diamond orange pear loc1  .  +    0 
diamond orange pear loc2  .  +    0.22
diamond orange pear loc3  .  +    4.28 
 ......

I would like to do this in python. 我想在python中做到这一点。

with open('/path/to/file/') as inFile:
    inFile.next()
    for line in inFile:
        data = cols[6:]
        data = map(float,data)

        sum_3 = [sum[for x in x data[0:3]]
        sum_last = [sum[for x in x data[4:7]]
        average = sum_3/sum_last 

This doesn't work, and I was hoping if I could get some advice? 这不起作用,我希望可以得到一些建议吗?

You don't show where cols comes from, but it appears you didn't actually split each line, in which case you are left with is a single string and you were trying to work with the characters of that string, without the first 6. Mapping individual characters to float values is not going to give you the data you need. 您没有显示cols来源,但是看来您实际上并没有拆分每一行,在这种情况下,您剩下的只是一个字符串,并且您尝试使用该字符串的字符,而没有前6个字符。将单个字符映射到浮点值不会为您提供所需的数据。

Next, sum() is a function, but you are using indexing syntax, sum[...] will throw an exception. 接下来, sum()是一个函数,但是您正在使用索引语法, sum[...]将引发异常。 You don't need to use a list comprehension for getting values out of a slice either, just sum(data[:3]) would do, provided the slice produces a sequence of float s. 您也不需要使用列表推导从切片中获取值,只要sum(data[:3])会做,只要切片产生一个float序列即可。

You have a tab-delimited file, it is probably easiest to just use the csv module to do the splitting: 您有一个制表符分隔的文件,使用csv模块进行拆分可能是最简单的:

import csv

with open('/path/to/file/') as infile:
    reader = csv.reader(infile, delimiter='\t')
    next(reader)  # skip first row

    for row in reader:
        first3, last = row[-7:-4], row[-4:]
        try:
            average = sum(map(float, first3)) / sum(map(float, last))
        except ZeroDivisionError:
            # last four values are all zero; just set the average to zero.
            average = 0

I've made allowances for the last 4 values all being zero; 我对最后四个值全部为零留有余量。 at that point you'd be dividing by zero and you'd want to handle the exception that is thrown for that case. 到那时,您将被零除,并且您想处理针对该情况引发的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM