python - 如何将包含短语的 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:“我喜欢烹饪”
但是我试过没有空格或标点符号的代码,我得到了一个实际值,但我确实需要考虑这些字符。
解决方案
为了扩展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']
推荐阅读
- c++ - 恢复作为模板给出的通用集合的类型
- sql - Oracle 正则表达式匹配最后一次出现的字符串
- flutter - Container 中的固定高度在 Flutter 中不起作用
- php - 循环 2 个差异表并在 XML 中输出结果
- microsoft-graph-api - Microsoft Graph API 获取 callRecord 方法:callRecord 的版本
- cockroachdb - 在 CockroachDB 中,我如何确定一个查询使用了多少内存?
- node.js - Bookshelfjs 在哪里和哪里销毁
- elasticsearch - 出现错误“未找到 [logdata.timestamp] 的映射以便排序”
- rust - 如何使用多个内核编译单个 crate?
- python - Google Assistant API,控制连接到 Google Home 的电灯开关