【问题标题】:How to search through an arry containing strings, and create a new array with only integers如何搜索包含字符串的数组,并创建一个只有整数的新数组
【发布时间】:2019-03-27 02:39:54
【问题描述】:

如果我有一个仅包含字符串的数组,但其中一些是数字,我将如何搜索数组,确定哪些字符串实际上是数字,并将这些数字添加到新数组中?数组示例如下: [ "Chris" , "90" , "Dave" , "76" ]

我尝试过使用 for 循环在每个索引上连续使用 isdigit(),如果是,则将该项目添加到新数组中。

scores = []
    for i in range(len(name_and_score_split)):
        if name_and_score_split[i].isdigit() == True:
            scores.append(name_and_score_split[i])

运行上述代码时,它告诉我列表数据类型没有“isdigit”功能 编辑:我发现我的问题是列表实际上是列表列表。

【问题讨论】:

  • 到底是什么问题?您的代码目前正在执行此操作,您是否在问这是否是正确的方法?

标签: python arrays string search int


【解决方案1】:

使用列表理解并利用 Python for 的 for-each 属性,而不是遍历索引:

lst = ["Chris" , "90" , "Dave" , "76"]

scores = [x for x in lst if x.isdigit()]
# ['90', '76']

或者,filter 你的名单:

scores = list(filter(lambda x: x.isdigit(), lst))

【讨论】:

    【解决方案2】:

    假设您正在尝试对整数执行以下操作:

    // 采用from 并将float 更改为int

    def is_number(s):
        try:
            int(s)
            return True
        except ValueError:
            return False
    

    那你就可以了

    [x for x in name_and_score_split if is_number(x)]
    

    【讨论】:

      【解决方案3】:

      如果你想要 int 列表:

      s = ["Chris", "90", "Dave", "76"]
      e = [int(i) for i in s if i.isdigit()]
      print(e)
      # OUTPUT: [90, 76]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-23
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多