0

我有一个表,其中包含:

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]]

我如何将每个序数表示包含在上面的列表中的单个列表中?我是否为此目的引入一个新列表?

4

5 回答 5

1

对于第一个循环 ( for item in table),项目将是一个列表,而不是您预期的一个字符。

因此,您需要再次循环 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 和 recud 对表中每个字符的总和。

如下代码:

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]
于 2018-03-15T01:21:55.527 回答
1
tables = [['THEINCREDIBLES'],['IRONMAN']]
for table in tables:
    t= ''.join(table)
    h = 0
    for c in t:
        h = h + ord(c)
    print(h)
于 2018-03-15T01:25:28.837 回答
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]]
于 2018-03-15T01:29:44.317 回答
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]]
于 2018-03-15T01:16:55.477 回答
0

Ord() 仅适用于字符。Python 将字符表示为长度为 1 的字符串,而不是内存中只有足够空间容纳单个字符的对象。换句话说,它不区分字符串和字符。

您必须一次将字符串转换为一个字符。

[编辑]与我建议在地图函数中使用 ord() 的答案同时发布是一个很好的解决方案。不过,核心概念是一次将一个字符传递给 ord()。

于 2018-03-15T01:20:05.747 回答