嵌套字符串的顺序表示

2024-09-24 08:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张桌子,里面有:

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

如何将每个序数表示包含在上述列表中的单个列表中?为此,我需要引入一个新的列表吗?你知道吗


Tags: in列表fortable数字movie单词row
3条回答

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

因此,您需要再次循环项[0]以获取每个字符,然后执行ord。你知道吗

下面是简单的方法:

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对表中每个字符的ord求和。你知道吗

代码如下:

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]
tables = [['THEINCREDIBLES'],['IRONMAN']]
for table in tables:
    t= ''.join(table)
    h = 0
    for c in t:
        h = h + ord(c)
    print(h)

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

相关问题 更多 >