【问题标题】:Loop over string based on keys in dictionary (Python)基于字典中的键循环字符串(Python)
【发布时间】:2023-01-31 00:02:29
【问题描述】:

我不想遍历字符串的每个单独字符,而是想遍历字符串的一部分(多个字符)。这些部分由字典的键定义。

例子:

my_dict = {'010': 'a', '000': 'e', '1101': 'f', '1010': 'h', '1000': 'i', '0111': 'm', '0010': 'n', '1011': 's', '0110': 't', '11001': 'l', '00110': 'o', '10011': 'p', '11000': 'r', '00111': 'u', '10010': 'x'}
word = "1000001001100001100000100000110"
output = ""

我试过的(确实是分别循环遍历每个字符):

for i in word:
   letter = my_dict[i]
   output += letter
   word = word.lstrip(letter)

我的输出:

"KeyError: '1'"

但我想获得键“1000”及其值“i”,然后继续使用键“0010”并获得其值“n”等...

预期输出:

# Expected output:
output = "internet"

【问题讨论】:

    标签: python string loops dictionary


    【解决方案1】:

    你可以在 word 上做一个 while 循环,每次都删除你在 dict 中找到的部分。当 words 为空时,你将停止循环,程序结束。

    while word:
        for key, value in my_dict.items():
            if word.startswith(key):
                print(value, end="")
                word = word[len(key):]
                continue
    

    【讨论】:

      猜你喜欢
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多