You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python布尔值函数filteredFastaToYear调用失效函数filterHeaderToYear导致过滤结果为空的调试求助

Fixing Your Python Fasta Filtering Functions

Let's walk through the issues in your code step by step and get it working as expected:

1. Critical Logic Error in filterHeaderToYear

Your current filterHeaderToYear is built to accept a list of headers, but in your loop, you're passing it a single header string (like '2021-2'). This means when you run for header in listOfHeaders, you're actually iterating over each character of the string instead of processing the header itself. We need to rewrite this function to handle a single header directly:

def filterHeaderToYear(year, header):
    """Check if the header belongs to the specified year; return the year if match, else False"""
    header_split = header.split('-')
    if header_split[0] == year:
        return year  # Return the year string to use in our output headers
    return False

2. Fixes in filteredFastaToYear

There are three key issues in this function:

  • Loop range mistake: range(0, len(listOfHeaders)-1) skips the last element entirely. Use range(len(listOfHeaders)) to iterate through every item in the list.
  • Incorrect condition check: You're comparing the boolean return value of filterHeaderToYear to the year string, which will never be true. Instead, check if the function returns a truthy value (the matched year string).
  • Header formatting mismatch: Your expected output needs headers trimmed to just the year, not the full original header. We'll use the returned year from filterHeaderToYear for this.

Here's the corrected function:

def filteredFastaToYear(year, listOfSequences, listOfHeaders):
    """Output filtered sequence list and header list"""
    filtListOfSequences = []
    filtListOfHeaders = []
    
    for i in range(len(listOfHeaders)):
        matched_year = filterHeaderToYear(year, listOfHeaders[i])
        if matched_year:
            filtListOfSequences.append(listOfSequences[i])
            filtListOfHeaders.append(matched_year)
    
    return filtListOfSequences, filtListOfHeaders

3. Test the Corrected Code

Let's run your original test case to verify:

sequences_inp = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']
headers_inp = ['2019-9', '2021-2', '2020-1', '2021-5', '2021-8']

sequences_out, headers_out = filteredFastaToYear('2021', sequences_inp, headers_inp)
print(len(sequences_out), len(headers_out))  # Output: 3 3
print(sequences_out)  # Output: ['DEF', 'JKL', 'MNO']
print(headers_out)    # Output: ['2021', '2021', '2021']

This will now produce exactly the output you expected!

内容的提问来源于stack exchange,提问作者Marija

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:17:41