python - 如何将包含短语的 str 列表转换为 int 列表?

标签 python python-3.x

我有一个脚本,允许我将从 Excel 获得的信息提取到列表中,该列表包含 str 值,其中包含以下短语:“我喜欢 cooking ”、“我的狗的名字是 Doug”等。

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

我使用的代码是:

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

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

运行代码时出现以下错误:

builtins.ValueError: invalid literal for int() with base 36: "I like cooking"

但是我尝试了不带空格或标点符号的代码,并且得到了实际值,但我确实需要考虑这些字符。

最佳答案

要扩展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']

关于python - 如何将包含短语的 str 列表转换为 int 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56939740/

相关文章:

Python:字符串替换索引

python - 打开文件并在一行中对该文件执行操作是否会关闭该文件?

python - 如何检查给定的 Python 环境是否是 PipEnv

python - urllib.request.urlopen 超时没有互联网

python - 获取 postgresql 唯一日期的内存有效方式?

python - 用 Pandas 导入数据时卡住了错误

python - 在 Pandas 中使用 fillna() 和 lambda 函数替换 NaN 值

python - Boto3上传ServerSideEncryption

python - 使用 numpy 将时间平均值恢复为即时值

python - 循环到占位符文本 block 并连接每个文本 block