这是我的代码,我觉得这应该有效。我刚刚添加了zipcode = str(zipcode)以查看它是否可以正常工作,所以我可能会把它拿出来,只是让原始的zipcode成为一个字符串。我需要它是一个字符串,因为我不希望二进制数实际上添加到彼此。当我在python shell中初始化函数时,它只返回任何内容
def digitConvert(zipcode):
zipcode = str(zipcode)
n = 0
binary = ""
while n < len(zipcode):
if zipcode[n] == 0:
binary = binary + "11000"
n = n + 1
elif zipcode[n] == 1:
binary = binary + "00011"
n = n + 1
elif zipcode[n] == 2:
binary = binary + "00101"
n = n + 1
elif zipcode[n] == 3:
binary = binary + "00110"
n = n + 1
elif zipcode[n] == 4:
binary = binary + "01001"
n = n + 1
elif zipcode[n] == 5:
binary = binary + "01010"
n = n + 1
elif zipcode[n] == 6:
binary = binary + "01100"
n = n + 1
elif zipcode[n] == 7:
binary = binary + "10001"
n = n + 1
elif zipcode[n] == 8:
binary = binary + "10010"
n = n + 1
elif zipcode[n] == 9:
binary = binary + "10100"
n = n + 1
return binary
感谢您的帮助!
答案 0 :(得分:1)
如果我理解正确,邮政编码是一个整数。这是一个将整数转换为二进制的小python函数。默认是你想要24位二进制。
def int2bin(n, count=24):
"""returns the binary of integer n, using count number of digits"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
例如,我的邮政编码为60517,所以我会这样做:
>>> print int2bin(60517)
000000001110110001100101
如果我只想要16个二进制位:
>>> print int2bin(60517, 16)
1110110001100101
答案 1 :(得分:0)
主要问题是zipcode[n]
是一个字符,而不是一个数字,因此它永远不会与数字相等(Python不会自动转换它们)。您还可以进行一些简化,例如使用for
循环而不是索引字符串,并使用字典从十进制数字映射到二进制字符串。
def digitConvert(zipcode):
zipcode = str(zipcode)
digitMap = { '0': '11000', '1': '00011', '2': '00101', ... }
binary = ""
for digit in zipcode:
if digit in digitMap:
binary += digitMap[digit]
return binary
答案 2 :(得分:0)
我没有看到您的代码有任何问题...除了缩进和检查if
条件。
def digitConvert(zipcode):
zipcode = str(zipcode)
n = 0
binary = ""
while n < len(zipcode):
if zipcode[n] == '0':
binary = binary + "11000"
elif zipcode[n] == '1':
binary = binary + "00011"
elif zipcode[n] == '2':
binary = binary + "00101"
elif zipcode[n] == '3':
binary = binary + "00110"
elif zipcode[n] == '4':
binary = binary + "01001"
elif zipcode[n] == '5':
binary = binary + "01010"
elif zipcode[n] == '6':
binary = binary + "01100"
elif zipcode[n] == '7':
binary = binary + "10001"
elif zipcode[n] == '8':
binary = binary + "10010"
elif zipcode[n] == '9':
binary = binary + "10100"
n = n + 1
return binary
更新
您可以简化整个过程:
def digitConvert(zipcode):
zipcode = str(zipcode)
x = {
"0" : "11000",
"1" : "00011",
"2" : "00101",
"3" : "00110",
"4" : "01001",
"5" : "01010",
"6" : "01100",
"7" : "10001",
"8" : "10010",
"9" : "10100"
}
return "".join(x[i] for i in zipcode if i in x)