python将列表转为整型
时间: 2023-06-10 20:02:40 浏览: 91
你可以使用列表推导式和内置函数 int() 来实现将列表转为整型。具体实现代码如下:
```
lst = ['1', '2', '3', '4']
int_lst = [int(x) for x in lst]
```
这样就将列表 lst 中的每个元素都转换为对应的整型数值,并存储在新的列表 int_lst 中。
相关问题
python将列表中的数据从字符串转为整形
可以使用列表推导式和 int() 函数将列表中的字符串转换为整数类型,例如:
```python
str_list = ['1', '2', '3', '4']
int_list = [int(x) for x in str_list]
print(int_list) # [1, 2, 3, 4]
```
另外,也可以使用 map() 函数将列表中的每个元素都应用一个函数,例如:
```python
str_list = ['1', '2', '3', '4']
int_list = list(map(int, str_list))
print(int_list) # [1, 2, 3, 4]
```
python将数组类型转为整形
可以使用NumPy库中的astype()方法将数组类型转为整型。例如:
```python
import numpy as np
a = np.array([1.2, 2.3, 3.4])
b = a.astype(int)
print(b)
```
输出结果为:
```
[1 2 3]
```
astype()方法将数组中的元素类型转为int型。如果想转为其他类型,只需要将int替换为其他类型即可。
阅读全文
相关推荐















