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

遍历元组列表并按元素值合并字符串(禁用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 to new_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_chars list.
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:51:29