【问题标题】:Python - print dict key from value within string orderPython - 从字符串顺序中的值打印字典键
【发布时间】:2017-12-02 18:59:27
【问题描述】:

我有以下代码:

d = {'one' : '11111111', 'two' : '01010101', 'three' : '10101010'}

string = '01010101 11111111 10101010'

text = ''

for key, value in d.items():
    if value in string:
        text += key
print(text)

输出:一二三

然而,我想要的输出是字符串的顺序,所以:twoonethree。在 python 中使用字典时这可能吗?谢谢!

【问题讨论】:

    标签: string python-3.x dictionary


    【解决方案1】:

    反转你的 dict(d) 会有所帮助:

    val2key = {value: key for key, value in d.items()}
    text = "".join(val2key[value] for value in string.split())
    print(text)
    

    二一三

    【讨论】:

    • 太棒了!是否还会说字符串没有空格,例如:010101011111111110101010
    • 是的,只需将 string.split() 替换为 textwrap.wrap(string, 8)
    【解决方案2】:

    一种解决方案是将字符串拆分为一个列表,并为该列表中的每个项目循环。

    编辑: split() 方法使用分隔符返回所有单词的列表,在这种情况下使用空白空格(如果是空格,您可以将其称为 string.split()方式。)

    dict = {'one' : '11111111', 'two' : '01010101', 'three' : '10101010'}
    
    string = '01010101 11111111 10101010'
    
    text = ''
    
    for item in string.split(" "):
        for key, value in dict.items():
            if value == item:
                text += key + " "
    print(text)
    

    输出:two one three

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      相关资源
      最近更新 更多