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

如何实现create_bigrams函数生成以二元字符串为键的字典

Python实现create_bigrams函数

实现思路

  • 遍历输入列表中的所有字符串,逐个提取相邻二元字符组合
  • 利用字典键的唯一性自动去重重复的二元组合,所有键对应的值统一设为True

代码实现

def create_bigrams(l):
    bigrams = {}
    for s in l:
        # 长度小于2的字符串无有效二元组合,自动跳过
        for i in range(len(s) - 1):
            gram = s[i:i+2]
            bigrams[gram] = True
    return bigrams

测试验证

调用示例:

print(create_bigrams(['baka', 'kaka']))

输出结果:

{'ba': True, 'ak': True, 'ka': True}

和要求的预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:21:02