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. Userange(len(listOfHeaders))to iterate through every item in the list. - Incorrect condition check: You're comparing the boolean return value of
filterHeaderToYearto theyearstring, 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
filterHeaderToYearfor 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
相关产品推荐
相关产品推荐

