我有一张桌子,里面有:
table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']]
我想把表中每个列表中的单词转换成它的数字表示(ASCII)。你知道吗
我试过:
movie = 'THEINCREDIBLES'
h = 0
for c in movie:
h = h + ord(c)
print(h)
但如果我使用上表中的列表,我会得到一个错误,说ord expected string of length 1
table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']]
h = 0
for c in table:
h = h + ord(c)
print(h)
为@Sphinx编辑
我做过:
table = [[1,'THEINCREDIBLES'],[2,'IRONMAN']]
h = 0
ordlist = []
for row in table:
for c in row[1]:
h = h + ord(c)
ordlist.append(row[0])
oralist.append(h)
h = 0
print(ordlist)
现在我的输出是:
[1,1029,2,532]
几乎接近我想要的是:
[[1,1029],[2,532]]
如何将每个序数表示包含在上述列表中的单个列表中?为此,我需要引入一个新的列表吗?你知道吗
对于第一个循环(
for item in table
),项将是一个列表,而不是预期的一个字符。你知道吗因此,您需要再次循环项[0]以获取每个字符,然后执行ord。你知道吗
下面是简单的方法:
也可以使用map和recude对表中每个字符的ord求和。你知道吗
代码如下:
以上两个代码输出:
bytes
类型可能正是您想要的,它将一个字符串转换成一个不可变的ascii值序列。你知道吗现在您需要的是仅将其应用于
table
中的嵌套字符串。你知道吗相关问题 更多 >
编程相关推荐