【问题标题】:Assigning a list to a slice of another and converting the indexes to a different type将列表分配给另一个列表并将索引转换为不同的类型
【发布时间】:2021-03-01 05:45:25
【问题描述】:

比如说我有一个列表

list1 = ["George", "47", "62", "71", "Apples"] 

有没有办法我可以做类似list2 = list1[1:4] 的事情,同时将所有这些值转换为整数,或者至少在之后。

编辑: 我刚刚实现的是在分配它之后(所以在这种情况下是在list2 = list1[1:4]之后)我做了一个for循环,格式如下

for i in range(len(list2) :
   list2[i] = int(list2[i])

我觉得这不是最优雅的方式,所以我仍然会很感激任何意见,因为我有多个列表我需要这样做,所以多次这样做感觉...马虎地说最少。

【问题讨论】:

    标签: python python-3.x list types


    【解决方案1】:

    我想你正在寻找map()

    例如:

    >>> list(map(int,['01','02','03']))
    [1, 2, 3]
    

    【讨论】:

      【解决方案2】:

      答案取决于您想要做到的万无一失。最简单的方法是映射suggested by user1104372。您也可以使用list comprehension

      list1 = ["George", "47", "62", "71", "Apples"] 
      list2 = [int(i) for i in list1[1:4]]
      >>>[47, 62, 71]
      

      如果你有一个混合列表,这将不起作用,所以我们必须检查字符串是否是整数表示:

      list1 = ["George", "47", "62.3", "Bahamas", "71", "Apples"] 
      list2 = [int(i) for i in list1[1:5] if i.isnumeric()]
      >>>[47, 71]
      

      很遗憾,这不包括负数。我们可以使用regex 来完成更复杂的解析任务:

      import re
      list1 = ["George", "+47", "62.3", "Bahamas", "-71", "Apples"] 
      list2 = [int(i) for i in list1[1:5] if re.match("[-+]?\d+$", i)]
      >>>[47, -71]
      

      后者可以扩展到更复杂的情况,例如“39.000”,它是整数的表示 - 但这超出了您的问题范围。

      【讨论】:

      • 非常感谢!这是我要求的更多信息,但方式非常好。我很感激!
      • 很高兴能提供帮助。当我开始使用 Python 时,range(len(list2) 是我的首选风格,直到我注意到你应该直接使用 for egg in eggbasket: 或者,如果你真的需要索引(你很少这样做)for i, egg in enumerate(eggbasket):。这让生活变得如此轻松。
      猜你喜欢
      • 1970-01-01
      • 2012-06-24
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多