这是我的代码,我觉得这应该是工作。我刚才添加了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
谢谢你的帮助!你知道吗
如果我理解正确,邮政编码是一个整数。下面是一个将整数转换为二进制的小python函数。默认值是需要24位二进制。你知道吗
例如,我的邮政编码是60517,所以我会这样做:
如果我只需要16个二进制位:
主要问题是
zipcode[n]
是一个字符,而不是一个数字,因此它永远不会与数字进行比较(Python不会自动转换它们)。您还可以进行一些简化,例如使用for
循环而不是索引字符串,以及使用字典将十进制数字映射到二进制字符串。你知道吗我看你的代码没有问题。。。除了缩进和检查
if
条件。你知道吗更新:
您可以将整个过程简化为:
相关问题 更多 >
编程相关推荐