遍历元组列表并按元素值合并字符串(禁用itertools.groupby)
Solution for Grouping Non-Consecutive Tuples by Second Value
Got it, let's tackle this problem without using itertools.groupby—since we need to keep non-consecutive entries with the same second value as separate groups (like the 'a' and 'g' both tied to 1). Here's a simple, straightforward approach that works by tracking our current group as we iterate through the list:
Step-by-Step Implementation
li = [('a',1),('b',2),('c', 2),('d', 2), ('e', 3), ('f', 3), ('g', 1)] new_li = [] current_key = None current_chars = [] for char, key in li: # When we hit a new key, wrap up the previous group if it exists if key != current_key: if current_key is not None: new_li.append((''.join(current_chars), current_key)) # Reset for the new group current_key = key current_chars = [char] # Same key? Add the character to our current group's cache else: current_chars.append(char) # Don't forget to add the final group after the loop finishes if current_key is not None: new_li.append((''.join(current_chars), current_key)) print(new_li) # Output: [('a', 1), ('bcd', 2), ('ef', 3), ('g', 1)]
How This Works
- We initialize an empty result list (
new_li), plus two variables to track the current group's key and the characters we've accumulated for that group. - As we loop through each tuple:
- If the current tuple's key doesn't match our tracked
current_key, we first add the completed previous group tonew_li(if there was one), then reset our tracker variables for the new group. - If the key matches, we just add the current character to our
current_charslist.
- If the current tuple's key doesn't match our tracked
- After the loop ends, we have to add the last remaining group to
new_li—since the loop won't trigger the "new key" logic for the final set of characters.
This approach is easy to follow, doesn't require any external libraries, and perfectly handles your requirement of keeping non-consecutive same-key groups separate.
内容的提问来源于stack exchange,提问作者pythonista
相关产品推荐
相关产品推荐

