python怎么将字符串转换为数字

python如何将列表中的字符串转为数字?具体方法如下:

有一个数字字符的列表:

numbers = ['1', '5', '10', '8']

想要把每个元素转换为数字:

numbers = [1, 5, 10, 8]

用一个循环来解决:

new_numbers = []; for n in numbers:   new_numbers.append(int(n)); numbers = new_numbers;

有没有更简单的语句可以做到呢?

1、遍历

numbers = [ int(x) for x in numbers ]

2、Python2.x,可以使用map函数

numbers = map(int, numbers)

如果是3.x,map返回的是map对象,当然也可以转换为List:

numbers = list(map(int, numbers))

3、还有一种比较复杂点:

for i,v in enumerate(numbers):     numbers[i] = int(v)
标签:
来源: WordPress导航主题
日期: 2023-4-26
作者: WordPress导航主题
阅读数: 105
链接到文章: https://www.gkxyz.com/pythonzenmejiangzifuchuanzhuanhuanweishuzi.html

推荐站点

  • RAKsmart

    主机商介绍:RAKsmart是知名的美国服务器租用商,包括美国站群服务器、美国cn2服务器、香港服务器等热门产 […]

  • Vultr

    Vultr Global Cloud Hosting – Brilliantly Fast SSD […]

  • 阿里云-为了无法计算的价值

    阿里云——阿里巴巴集团旗下公司,是全球领先的云计算及人工智能科技公司之一。提供免费试用、云服务器、云数据库、云 […]

评论已关闭