python - 函数未正确写入 .xls。 Python 2.7.1

标签 python string function export-to-excel

当我检查 Excel 文件时,它只写入最后输入的一行数据。

def Table(fn,fe):

       for fseq in fn:
              count=0
              for k in fseq:
                     if k=='G' or k=='C':
                            count=count+1
              percentage=(float(count)/len(fseq))*100
              fin=open(fe,'w')
              table=str(fseq)+'\t'+str(count)+'\t'+str(percentage)+'\n'
              fin.write(table)
       return fe



tablist=["AAUG","GCGA","AGCG","TCGA"]
fout=Table(tablist, 'abc.xls')

它应该输出:

   AAUG    1   25.0
   GCGA    3   75.0
   AGCG    3   75.0
   TCGA    2   50.0

相反,我的输出如下所示:

   TCGA    2   50.0

并返回正在写入的文件的名称。

为什么只为字符串的最后一个元素写入数据?

最佳答案

您的 for 循环是在字符串上循环,而不是每个字符串的字符。试试这个:

   for k in fn:
       for c in k:
          if c=='G' or c=='C':
                 count=count+1

(else:不是必需的。)

您还需要将编写代码的文件移到外循环内部,以便使报告正确(但将打开移到外循环上方)。

关于python - 函数未正确写入 .xls。 Python 2.7.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380516/

相关文章:

Python删除所有文件夹但不删除文件

将一维字符串复制到二维数组元素中

python - 两个函数的 yield 可以相减吗?

java - Java 中的字符串标记化(大文本)

php - 将 mysql 查询的结果对象获取到函数中的问题

python - 值错误: could not convert string to float: '-0,274697\n'

python - 这个函数每次都会创建一个新的 TensorFlow 图吗?

python - 使用 whoosh 进行智能字符串搜索 python(也许)

java - 问题模式/匹配器

c - 是否需要初始化 char 数组以获得准确的长度?