python - 如果字典在列表中,如何将它们的值从字符串更改为 int

标签 python list dictionary casting typeerror

我有一本字典作为

maketh = {'n':['1', '2', '3'], 'g': ['0', '5', '6', '9'], ' ca': ['4', '8', '1', '5', '9', '0']}

我打算改成

maketh_new = {'n':[1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}

数字在值中的顺序非常重要。所以,顺序应该保持不变 即使在更改之后。

当我尝试使用任何可用的在线方法更改它时,我总是遇到的错误是:

TypeError: int() 参数必须是字符串、类字节对象或数字,而不是“列表”

“如果有任何打字错误,请忽略...”

我自己写的一个可能像这样的东西可以工作的是:

maketh_new = dict()

for (key, values) in maketh.items():
    for find in len(values):
        maketh_new [key] = int(values[find])   

我试过它,想如果我可以访问列表中值的所有元素作为字符串,那么我可以将它键入 cast 为 int。但是我得到一个错误:

'list' object cannot be interpreted as an integer 

所以如果有人能帮我找到解决办法,请去做...

最佳答案

假设值中的所有元素都是数字,您可以在值上map int:

maketh_new = {k: list(map(int, v)) for k, v in maketh.items()}

输出:

{'n': [1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}

如果没有,您可以使用 str.isdigit 来更安全地输入:

maketh = {'n':['1', '2', 'a'],  # Note 'a' at last
          'g': ['0', '5', '6', '9'], 
          'ca': ['4', '8', '1', '5', '9', '0']}

maketh_new = {k: [int(i) if i.isdigit() else i for i in v] for k, v in maketh.items()}

输出:

{'n': [1, 2, 'a'], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}

关于python - 如果字典在列表中,如何将它们的值从字符串更改为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71584217/

相关文章:

python - 使用Python的Facebook API

apache-flex - 检查 Flex 中的 key 是否可用

python - 用字典理解替换两个嵌套循环

python - 将多个键/值设置到字典中(python 2.72)

c++ - map中operator[]插入的指针类型的值是否总是NULL?

python - 属性错误: 'builtin_function_or_method' object has no attribute 'split' 3. 7

python - Spyder (Python 3.7) 启动时出现一个黑色窗口。我该如何修复它?

python - 如何使用远程 pdb 连接调试在 Heroku 上运行的 Django 应用程序?

java - 如何将ArrayList中的每个数字放入变量中

python - 如果子列表的第一个元素在 Python 中是唯一的,则从第一个子列表中获取前两项