如何从 Python 2.7 中以空格分隔的字符串中提取整数? [英] How to extract integers from a string separated by spaces in Python 2.7?

查看:41
本文介绍了如何从 Python 2.7 中以空格分隔的字符串中提取整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符串中提取整数,其中整数用空格分隔,即''.我怎么能这样做??

输入

I='1 15 163 132'

结果:

[1,15,163,132]

所以我写了一个这样的函数

def getIt(aStr):收集 = []我=0当我 <len(aStr):打印('i = ' + str(i))如果 aStr[i]!=' ':j=0而 aStr[i+j]!=' ' 或 (i+j)<=len(aStr)-1:打印('j = '+str(j))j+=1如果 i+j==len(aStr):collect.append(int(aStr[i:i+j-1]))别的:collect.append(int(aStr[i:i+j]))i+=j+1别的:我+=1返回收集

当我删除条件时代码运行完美

while aStr[i+j]!=' ':# or (i+j)<=len(aStr)-1:

并在每个输入字符串的末尾放置一个空格.请告知我哪里出错了?

解决方案

试试这个代码:

myIntegers = [int(x) for x in I.split()]

<小时>

解释:

<小时>

其中 s 是您要拆分的字符串,a 是您要用作分隔符的字符串.然后:

s.Split(a)

在出现 a 的点处拆分字符串 s,并返回已拆分的子字符串列表.

如果没有提供参数,例如:s.Split()那么它默认使用空格(如空格、制表符、换行符)作为分隔符.

具体来说,就您而言:

I = '1 15 163 132'I = I.split()打印(一)

<块引用>

[1"、15"、163"、132"]

它创建一个字符串列表,在您的特定示例中有空格的那些点处分开.

这是官方的 python 关于字符串 split() 方法的文档.

<小时>

现在我们使用所谓的列表推导将列表中的每个元素转换为整数.

myNewList = [myOtherList 中 x 的操作]

以下是它正在做的事情的细目:

  • 假设 myOtherList 是一个列表,包含一些元素,
  • 然后我们将一次临时存储一个元素为 x
  • 我们将对 myOtherList
  • 中的每个元素执行一些操作
  • 假设我们执行的这个操作有一些返回值,
    • 然后返回的值将作为一个元素存储在我们正在创建的新列表中
  • 最终结果是我们将填充一个新列表 myNewList,其长度与 myOtherList
  • 完全相同

具体来说,就您而言:

myIntegers = [int(x) for x in I.split()]

执行以下操作:

  • 我们看到 I.split() 返回 ["1", "15", "163", "132"]
  • 对于这些字符串元素中的每一个,只需将它们转换为整数
  • 并将该整数作为元素存储在新列表中.

查看官方 python 关于列表推导式的文档了解更多信息信息.

希望对你有帮助.

I want to extract integers from a string in which integers are separated by blank spaces i.e ' '. How could I do that ??

Input

I='1 15 163 132'

Result:

[1,15,163,132]

So I wrote a function which goes like this

def getIt(aStr):
collect = []
i=0
while i < len(aStr):
    print('i = ' + str(i))
    if aStr[i]!=' ':
        j=0
        while aStr[i+j]!=' ' or  (i+j)<=len(aStr)-1:
            print('j = '+str(j))
            j+=1
        if i+j==len(aStr):    
            collect.append(int(aStr[i:i+j-1]))
        else:
            collect.append(int(aStr[i:i+j]))
        i+=j+1

    else:
        i+=1  
return collect

The code runs perfectly when I remove the condition

while aStr[i+j]!=' ':# or  (i+j)<=len(aStr)-1:

And place a blank space at the end of every input string. Please inform where am I going wrong?

解决方案

Try this code:

myIntegers = [int(x) for x in I.split()]    


EXPLANATION:


Where s is the string you want to split up, and a is the string you want to use as the delimeter. Then:

s.Split(a)

Splits the string s, at those points where a occurs, and returns a list of sub-strings that have been split up.

If no argument is provided, eg: s.Split() then it defaults to using whitespaces (such as spaces, tabs, newlines) as the delimeter.

Concretely, In your case:

I = '1 15 163 132'
I = I.split() 
print(I)

["1", "15", "163", "132"]

It creates a list of strings, separating at those points where there is a space in your particular example.

Here is the official python documentation on the string split() method.


Now we use what is known as List Comprehensions to convert every element in a list into an integer.

myNewList = [operation for x in myOtherList]

Here is a breakdown of what it is doing:

  • Assuming that myOtherList is a list, with some number of elements,
  • then we will temporarily store one element at a time as x
  • and we will perform some operation for each element in myOtherList
  • assuming that this operation we perform has some return value,
    • then the returned value will be stored as an element in a new list that we are creating
  • The end result is that we will populate a new list myNewList, that is the exact same length as myOtherList

Concretely, In your case:

myIntegers = [int(x) for x in I.split()]    

Performs the following:

  • We saw that I.split() returns ["1", "15", "163", "132"]
  • for each of these string elements, simply convert them to an integer
  • and store that integer as an element in a new list.

See the official python documentation on List Comprehensions for more information.

Hope this helps you.

这篇关于如何从 Python 2.7 中以空格分隔的字符串中提取整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆