我正在尝试将ASCII字符列表转换为十进制值。我的代码非常简单:
values = ['A', '2', 'D', '3', '4', '6']
cvalues = []
for i in values:
if i < '10':
cvalues.append(ord(i) - 48)
else:
cvalues.append(ord(i) - 55)
print cvalues
我得到以下结果:
[10, -5, 13, -4, -3, -1]
即使我将48改为41,我的结果也是错误的。我总是得到相同的结果。任何人都可以帮我吗?
答案 0 :(得分:0)
不是将每个字符与字符串'10'进行比较,而是将它们与单个字符'9'进行比较:
if i <= '9':
答案 1 :(得分:0)
>>> values = ['A', '2', 'D', '3', '4', '6']
>>> cvalues = []
>>> for v in values:
... try:
... i = int(v) # See if it's even an int
... except ValueError:
... continue # Keep going if it's a letter or something invalid
... else:
... if 1 < i <= 9: # Compare as numbers, not strings
... cvalues.append(i) # Now append if it fits your range
...
>>> cvalues
[2, 3, 4, 6]
答案 2 :(得分:0)
我认为你试图将(0-9)设为0-9 int和(A-Z)为10-35: 请注意,这不会考虑(a-z)
values = ['A', '2', 'D', '3', '4', '6']
cvalues = []
for i in values:
i = i.upper()
if ord(i) < 58:
cvalues.append(ord(i) - 48)
else:
cvalues.append(ord(i) - 55)
print cvalues
[10,2,13,3,4,6]