在Python中将列表的内部值转换为整数

2024-04-20 13:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在处理stdin中的值之后,我在python程序中得到了以下列表:

[['92', '022'], ['82', '12'], ['77', '13']]

我试图将这些价值观作为:

[[92, 22], [82, 12], [77, 13]]

我尝试map值,但发现错误:

print map(int, s)
Traceback (most recent call last):
  File "C:/Users/lenovo-pc/PycharmProjects/untitled11/order string.py", line 13, in <module>
    print map(int, s)
TypeError: int() argument must be a string or a number, not 'list'

其中s是我的列表。你知道吗

好心,建议我什么是优化的方式使str列表转换成整数。你知道吗


Tags: 程序mapmost列表stringstdincallusers
1条回答
网友
1楼 · 发布于 2024-04-20 13:35:56

简单list comprehension

>>> [ list(map(int,ele)) for ele in l ]

#驱动程序值:

IN : l = [['92', '022'], ['82', '12'], ['77', '13']]
OUT : [[92, 22], [82, 12], [77, 13]]

错误:

TypeError: int() argument must be a string or a number, not 'list'

抛出,因为^{}函数在松散意义上采用了平坦的iterable或list/1D list。因为您要向它发送多维列表,所以它会遍历子列表并尝试对其应用函数,从而抛出错误。你知道吗

map(function, iterable, ...)

The iterable arguments may be a sequence or any iterable object; the result is always a list.

相关问题 更多 >