将列表中的所有字符串转换为int

本文翻译自:Convert all strings in a list to int

In Python, I want to convert all strings in a list to integers. 在Python中,我想将列表中的所有字符串转换为整数。

So if I have: 所以,如果我有:

results = ['1', '2', '3']

How do I make it: 我该如何做:

results = [1, 2, 3]

#1楼

参考:https://stackoom.com/question/UuxR/将列表中的所有字符串转换为int


#2楼

A little bit more expanded than list comprehension but likewise useful: 比列表理解要扩展一点,但同样有用:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

eg 例如

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Also: 也:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

#3楼

Use the map function (in Python 2.x): 使用map函数(在Python 2.x中):

results = map(int, results)

In Python 3, you will need to convert the result from map to a list: 在Python 3中,您需要将结果从map转换为列表:

results = list(map(int, results))

#4楼

Use a list comprehension : 使用列表理解

results = [int(i) for i in results]

eg 例如

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值