函数在for循环Python中不能正常工作

2024-06-25 23:44:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,格式如下:

AAAAATTTTTT
AAATTTTTTGGG
TTTDDDCCVVVVV

我试图计算一个字符在行首和行尾按顺序出现的次数。你知道吗

我编写了以下函数:

def getStartEnd(sequence):
    start = sequence[0]
    end = sequence[-1]
    startCount = 0
    endCount = 0

    for char in sequence:
        if char == start:
            startCount += 1
            if ( char != start):
                break

    for char in reversed(sequence):
        if char == end:
            endCount += 1
            if ( char != end):
                break

    return startCount, endCount

此函数独立于字符串。例如:

seq = "TTTDDDCCVVVVV"
a,b = getStartEnd(seq)
print a,b

但是当我插入for循环时,它只在文件的最后一行给出正确的值。你知道吗

file = open("Test.txt", 'r')

for line in file:
    a,b = getStartEnd(str(line))
    print a, b

Tags: 函数inforifstartseqendprint
2条回答

因为除了最后一行之外,其他行都包含换行符。你知道吗

尝试以下操作(删除尾随空格):

with open("Test.txt", 'r') as f:
    for line in f:
        a, b = getStartEnd(line.rstrip())
        print a, b

顺便说一句,下面代码中的( char != end )总是False。(与( char != start)相同)

for char in reversed(sequence):
    if char == end:
        endCount += 1
        if ( char != end): # always False because char == end
            break

你是说这个吗?你知道吗

for char in reversed(sequence):
    if char == end:
        endCount += 1
    else:
        break

使用^{}如何:

import itertools

def getStartEnd(sequence):
    start = sequence[0]
    end = sequence[-1]
    start_count = sum(1 for _ in itertools.takewhile(lambda ch: ch == start, sequence))
    end_count = sum(1 for _ in itertools.takewhile(lambda ch: ch == end, reversed(sequence)))
    return start_count, end_count

三件事。首先,在函数中,您可能打算使用以下结构break。你知道吗

for char in sequence:
    if char == start:
        startCount += 1
    else:
        break

for char in reversed(sequence):
    if char == end:
        endCount += 1
    else:
        break

其次,在文件中循环行时,不需要使用str函数将行转换为字符串。它们已经是弦了!你知道吗

第三,行包括换行符,它们是这样的:'\n'它们用来告诉计算机何时结束一行,何时开始一行。要除去它们,可以使用string的rstrip方法,如下所示:

file = open("Test.txt", 'r')

for line in file:
    a,b = getStartEnd(line.rstrip())
    print a, b
file.close()

相关问题 更多 >