Python的 - 从字符串值为了
问题描述:
内印刷字典键我有这样的下面的代码:Python的 - 从字符串值为了
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)
输出:onetwothree
然而,我的期望了说就是串的次序,所以:twoonethree。这在Python中使用字典时可能吗?谢谢!
答
倒车您的字典(d)将帮助:
val2key = {value: key for key, value in d.items()}
text = "".join(val2key[value] for value in string.split())
print(text)
twoonethree
答
一种解决方案是将字符串分割成该列表中的每个项目的列表和循环。
编辑: 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
太好了!也会有在客场这样说的字符串没有空格,例如:010101011111111110101010 – kieron
没错,只需更换** string.split()**有** textwrap.wrap(字符串,8)**。 –