首页 文章

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

提问于
浏览
411

在Python中,我想将列表中的所有字符串转换为整数 .

所以,如果我有:

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

我该怎么做:

results = [1, 2, 3]

2 回答

  • 279

    使用map函数(在Python 2.x中):

    results = map(int, results)
    

    在Python 3中,您需要将map的结果转换为列表:

    results = list(map(int, results))
    
  • 864

    使用list comprehension

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

    例如

    >>> results = ["1", "2", "3"]
    >>> results = [int(i) for i in results]
    >>> results
    [1, 2, 3]
    

相关问题