【发布时间】:2019-08-13 23:22:28
【问题描述】:
我正在尝试将字符串转换为 char 数组,然后循环遍历数组中的每个 char 并与字典键进行比较,然后如果它们匹配,则打印键值并移动到数组中的下一个字符
我收集了一些例子并试图在脑海中解决它。我是 python 新手,经过很长时间尝试教我 10 岁的儿子后,我又回到了编程作为一种爱好。他在谈论二进制,我说我们可以用 python 编写一个程序,例如可以将他的名字作为输入并以二进制代码打印他的名字。
#binary table is formatted such i have shortened it for simplicity
binaryTable = {
"a" : "01100001",
"b" : "01100010",
"c" : "01100011",
"d" : "01100100"
}
word = input('please input a value to see its representation in Binary Code: ')
def split(letters):
return [char for char in letters]
def members(dictArg, keysListArg):
count = 0
for x in newArray:
if newArray[x] == binaryTable.keys():
value = binaryTable.keys()
print(newArray[x])
print(' : ')
print(value)
count += 1
return count
def printBinary(dictArg, keysListArg):
count = 0
for list_item in keysListArg:
if list_item in dictArg:
count+= 1
print(count)
print(list_item)
print(' : ')
#print(keysListArg)
#print(dictArg) #print dictArg.Key() How to do this
print('\n')
return count
print('testing printBinary function\n')
newArray = split(word)
#members(newArray, binaryTable)
printBinary(newArray. binaryTable)
如果我说 abcd 我希望输出是 一个新的字典,其中的字符在 word 中带有它们的二进制键代表,或者只是在 for 循环迭代中打印字母键 #next 到代表性的二进制值,例如
j : 0110101
a : 0101010
m : 0101010
e : 0101010
s : 0101010
output:
1
a
:
2
e
:
3
j
:
4
m
:
5
s
:
['j', 'a', 'm', 'e', 's']
>>>
*为什么键出来的顺序不一样?
【问题讨论】:
-
什么版本的python?
dict用于在迭代时不保证键的顺序。不确定现在的行为。 stackoverflow.com/questions/5629023/… -
3.7 我这样编辑了函数,但它仍然以错误的顺序打印:
-
def printBinary(dictArg, keysListArg): count = 0 for list_item in keysListArg: if list_item in dictArg: count+= 1 print(count) print(list_item) print(' : ') x = keysListArg. get(list_item) print(x) 返回计数
-
我很难理解你在追求什么......但你的意思是把函数
printBinary称为printBinary(binaryTable, newArray)而不是printBinary(newArray, binaryTable)吗? -
我已经解决了:
标签: python string binary converters