我有一张包含以下内容的表:
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]]
如何将每个序数表示包含在列表中的单个列表中,如上所述?我是否为此目的引入了新的清单?
答案 0 :(得分:1)
对于第一个循环(for item in table
),item将是一个列表,而不是您预期的一个字符。
所以你需要再次循环使用item [0]来获得每个角色。
以下是直截了当的方式:
table = [['THEINCREDIBLES'],['IRONMAN']]
result = []
for row in table:
h = 0
for c in row[0]:
h = h + ord(c)
result.append(h)
print(result)
此外,您还可以使用map和recude对表格中每个字符进行求和。
以下代码:
from functools import reduce
table = [['THEINCREDIBLES'],['IRONMAN']]
print(list(map(lambda item: reduce(lambda pre, cur : pre + ord(cur), item[0], 0), table)))
以上代码输出:
[1029, 532]
[Finished in 0.186s]
答案 1 :(得分:1)
tables = [['THEINCREDIBLES'],['IRONMAN']]
for table in tables:
t= ''.join(table)
h = 0
for c in t:
h = h + ord(c)
print(h)
答案 2 :(得分:1)
bytes
类型可能正是您想要的,它会将字符串转换为不可变的ascii值序列。
title = 'THEINCREDIBLES'
sum(bytes(title.encode())) # 1029
现在您需要的是仅将其应用于table
。
table = [[1, 'THEINCREDIBLES'], [2, 'IRONMAN']]
new_table = [[id, sum(bytes(title.encode()))] for id, title in table]
# new_table: [[1, 1029], [2, 532]]
答案 3 :(得分:0)
您的table
列表中有列表。这可以通过列表压缩来解开。以下是与您的数据相关的一些示例。
movie = 'THEINCREDIBLES'
h1 = list(map(ord, movie))
# [84, 72, 69, 73, 78, 67, 82, 69, 68, 73, 66, 76, 69, 83]
table = [['THEINCREDIBLES'],['IRONMAN']]
h2 = [list(map(ord, m[0])) for m in table]
# [[84, 72, 69, 73, 78, 67, 82, 69, 68, 73, 66, 76, 69, 83],
# [73, 82, 79, 78, 77, 65, 78]]
答案 4 :(得分:0)
Ord()仅适用于角色。 Python将字符表示为长度为1的字符串,而不是内存中的对象,只有足够的空间用于单个字符。换句话说,它不区分字符串和字符。
您必须一次将字符串转换为一个字符。
[编辑]答案与我同时发布的建议在地图功能中使用ord()是一个很好的解决方案。但是,核心概念是你一次将一个角色传递给ord()。