我得到了列表的2D矩阵,其字符串如下:
somelist = [["12","10","0"]
["0","33","60"]]
我需要将所有str
转换为int
。
到目前为止我的代码是:
for i in somelist:
for j in i:
j = int(j)
答案 0 :(得分:2)
>>> [[int(i) for i in j] for j in somelist]
[[12, 10, 0], [0, 33, 60]]
答案 1 :(得分:2)
或使用地图:
1526299672891 geckodriver INFO geckodriver 0.20.1
1526299672895 geckodriver INFO Listening on 127.0.0.1:48641
1526299673899 mozrunner::runner INFO Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.YNIc2l05QiIr"
Running Firefox as root in a regular user's session is not supported. ($HOME is /home/test which is owned by test.)
这里是您的固定代码:
>>> [list(map(int, x)) for x in somelist]
[[12, 10, 0], [0, 33, 60]]
输出:
somelist = [["12","10","0"],
["0","33","60"]]
for n, i in enumerate(somelist):
for k, j in enumerate(i):
somelist[n][k] = int(j)
print(somelist)
答案 2 :(得分:2)
您的代码无效,因为Python中的int
是不可变类型。如果我更改一个int变量,它不会更改其地址中的值,但它会更改整个变量。因此,以前持有它的任何列表或对象都不会被更改。以下是一些例子:
In [1]: a_list = [1,2,3]
In [2]: var = a_list[0]
In [3]: var
Out[3]: 1
In [4]: id(var)
Out[4]: 4465792624
In [5]: var = 30
In [6]: id(var) # A different address
Out[6]: 4465793552
In [7]: a_list
Out[7]: [1, 2, 3]
In [8]: id(a_list[0])
Out[8]: 4465792624
In [9]: a_list[0] = 30
In [10]: a_list
Out[10]: [30, 2, 3]
这就是为什么如果你做这个小改动,你的代码就会起作用:
for i in somelist:
for ind, j in enumerate(i):
i[ind] = int(j)