Python列表中被0分隔的字符串合并问题求解(附测试用例)
Solution: Merge Strings Separated by Integer 0s
First, let's clarify the core rules we need to follow (derived from your test cases):
- Integer
0s act as separators (one or more count as a single separator) - String values (including
"0") are preserved as content - Consecutive content elements (no separators between them) stay as separate items
- Content elements separated by one or more
0s are merged into a single string - Leading/trailing
0s are ignored
Approach
The key insight is to split the input list into blocks of consecutive elements: either blocks of integer 0s or blocks of content strings. Then:
- Filter out all blocks of
0s - If there's only one content block, return it as-is (no merging needed)
- If there are multiple content blocks, merge all their elements into a single string and return it in a list
Implementation Code
def merge_strings_separated_by_zero(lst): # Split the list into blocks of consecutive 0s or non-0 content blocks = [] if not lst: return [] current_block = [lst[0]] for elem in lst[1:]: # Check if current element belongs to the same block type as the current block current_is_zero = isinstance(current_block[0], int) and current_block[0] == 0 elem_is_zero = isinstance(elem, int) and elem == 0 if current_is_zero == elem_is_zero: current_block.append(elem) else: blocks.append(current_block) current_block = [elem] blocks.append(current_block) # Keep only non-zero blocks non_zero_blocks = [block for block in blocks if not (isinstance(block[0], int) and block[0] == 0)] # Generate the result based on the number of non-zero blocks if not non_zero_blocks: return [] elif len(non_zero_blocks) == 1: return non_zero_blocks[0].copy() else: merged_content = ''.join(item for block in non_zero_blocks for item in block) return [merged_content]
Testing the Solution
Let's verify this against your test cases:
dataexp = [ (["a"], ["a"]), ([0,0,"a","b",], ["a","b"]), ([0,"a","0",], ["a","0"]), (["a",0,"b",], ["ab"]), (["a",0,0,"b",], ["ab"]), (["a","b",0], ["a","b"]), (["a","b","c"], ["a","b","c"]), (["a",0,"b",0, "c"], ["abc"]), ] for input_list, expected_output in dataexp: result = merge_strings_separated_by_zero(input_list) assert result == expected_output, f"Failed for input {input_list}: got {result}, expected {expected_output}" print("All test cases passed!")
Why Your Previous Attempts Might Have Failed
- List comprehensions: They're great for simple transformations but struggle with stateful logic (like tracking blocks and whether merging is needed across separators)
- Generator functions: While generators can handle state, it's easy to miss edge cases like multiple separators, leading/trailing separators, or distinguishing between single vs multiple content blocks. The block-based approach makes these cases explicit and easier to handle.
Notes for Your Django Template Use Case
Make sure the separators you're inserting are integer 0s, not string "0"s—since string "0" will be treated as content and preserved in the output. This should correctly suppress newlines when you use "\n".join() on the processed list, as merged content will be a single string without newlines between the merged parts.
内容的提问来源于stack exchange,提问作者JL Peyret
相关产品推荐
相关产品推荐

