我有一个脚本,允许我将从 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_bytes
和int.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/