首页 > 解决方案 > 如何将包含短语的 str 列表转换为 int 列表?

问题描述

我有一个脚本,允许我将从 excel 获得的信息提取到一个列表中,这个列表包含 str 值,其中包含诸如:“我喜欢烹饪”、“我的狗的名字是道格”等短语。

因此,我尝试了在 Internet 上找到的这段代码,知道 int 函数可以将实际短语转换为数字。

我使用的代码是:

lista=["I like cooking", "My dog´s name is Doug", "Hi, there"]

test_list = [int(i, 36) for i in lista]

运行代码我得到以下错误:

builtins.ValueError:int() 的无效文字,基数为 36:“我喜欢烹饪”

但是我试过没有空格或标点符号的代码,我得到了一个实际值,但我确实需要考虑这些字符。

标签: pythonpython-3.x

解决方案


为了扩展bytearray您可以使用的方法int.to_bytesint.from_bytes实际返回一个 int ,尽管整数将比您在示例中显示的要长得多。

def to_int(s):
    return int.from_bytes(bytearray(s, 'utf-8'), 'big', signed=False)

def to_str(s):
    return s.to_bytes((s.bit_length() +7 ) // 8, 'big').decode()

lista = ["I like cooking",
            "My dog´s name is Doug",
            "Hi, there"]

encoded = [to_int(s) for s in lista]

decoded = [to_str(s) for s in encoded]

编码:

[1483184754092458833204681315544679,
 28986146900667755422058678317652141643897566145770855,
 1335744041264385192549]

解码:

['I like cooking',
 'My dog´s name is Doug',
 'Hi, there']

推荐阅读