Python 迭代器行为

发布于 2024-12-29 11:38:26 字数 1677 浏览 1 评论 0原文

给定一个任意输入字符串,我的目的是找到该字符串中所有数字的总和。 这显然要求我在迭代字符串时知道字符串中的下一个元素......并决定它是否是整数。如果前一个元素也是整数,则这两个元素形成一个新整数,所有其他字符都将被忽略,依此类推。

例如,输入字符串

ab123r.t5689yhu8 

的总和应为 123 + 5689 + 8 = 5820

所有这一切都是在不使用正则表达式的情况下完成的。

我在 python 中实现了一个迭代器,我认为它的 (next()) 方法返回下一个元素,但是传递输入字符串

acdre2345ty 

我得到以下输出

a
c
d
r
e
2
4
t
y

一些数字 3 和 5 丢失了......这是为什么?我需要 next() 为我工作,以便能够筛选输入字符串并正确进行计算

更好的是,我应该如何实现下一个方法,以便将元素生成到在给定的迭代期间立即生效?

这是我的代码

class Inputiterator(object):
    '''
    a simple iterator to yield all elements from a given
    string successively from  a given input string
    '''
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def next(self):
        """
        check whether we've reached the end of the input
        string, if not continue returning the current value
        """
        if self.index == len(self.data)-1:
            raise StopIteration
        self.index = self.index + 1
        return self.data[self.index]

# Create a method to get the input from the user
# simply return a string

def get_input_as_string():
    input=raw_input("Please enter an arbitrary string of numbers")
    return input

def sort_by_type():
    maininput= Inputiterator(get_input_as_string())
    list=[]
    s=""
    for char in maininput:
        if str(char).isalpha():
            print ""+ str(char)
        elif str(char).isdigit() and str(maininput.next()).isdigit():
            print ""+ str(char)

sort_by_type()

Given an arbitrary input string I'm meant to find the sum of all numbers in that string.
This obviously requires that i know the NEXT element in string while iterating through it...and make the decision whether its an integer. if the previous element was an integer also, the two elements form a new integer, all other characters are ignored and so on.

For instance an input string

ab123r.t5689yhu8 

should result in the sum of 123 + 5689 + 8 = 5820.

All this is to be done without using regular expressions.

I have implemented an iterator in python, whose (next()) method i think returns the next element, but passing the input string

acdre2345ty 

I'm getting the following output

a
c
d
r
e
2
4
t
y

Some numbers 3 and 5 are missing...why is this? I need that the next() to work for me to be able to sift through an input string and do the calculations correctly

Better still, how should i implement the next method so that it yields the element to the immediate right during a given iteration?

Here is my code

class Inputiterator(object):
    '''
    a simple iterator to yield all elements from a given
    string successively from  a given input string
    '''
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def next(self):
        """
        check whether we've reached the end of the input
        string, if not continue returning the current value
        """
        if self.index == len(self.data)-1:
            raise StopIteration
        self.index = self.index + 1
        return self.data[self.index]

# Create a method to get the input from the user
# simply return a string

def get_input_as_string():
    input=raw_input("Please enter an arbitrary string of numbers")
    return input

def sort_by_type():
    maininput= Inputiterator(get_input_as_string())
    list=[]
    s=""
    for char in maininput:
        if str(char).isalpha():
            print ""+ str(char)
        elif str(char).isdigit() and str(maininput.next()).isdigit():
            print ""+ str(char)

sort_by_type()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

似狗非友 2025-01-05 11:38:26

Python 字符串已经是可迭代的,无需创建自己的迭代器。

因此,您想要的东西可以在没有迭代器的情况下简单地实现:

s = "acdre2345ty2390"

total = 0
num = 0

for c in s:
    if c.isdigit():
        num = num * 10 + int(c)
    else:
        total += num
        num = 0

total += num

这会导致:

>>> print total
4735

Python strings are already iterable, no need to create you own iterator.

What you want is thus simply achieved without iterators:

s = "acdre2345ty2390"

total = 0
num = 0

for c in s:
    if c.isdigit():
        num = num * 10 + int(c)
    else:
        total += num
        num = 0

total += num

Which results in:

>>> print total
4735
太阳男子 2025-01-05 11:38:26

这可以通过 itertools.groupby

from itertools import groupby

s = 'ab123r#t5689yhu8'
tot = 0
for k, g in groupby(s, str.isdigit):
    if k:
        tot += int(''.join(g))

或者在一行中(按照下面评论中的建议)

tot = sum((int(''.join(g)) for k, g in groupby(s, str.isdigit) if k)

This can be done with itertools.groupby:

from itertools import groupby

s = 'ab123r#t5689yhu8'
tot = 0
for k, g in groupby(s, str.isdigit):
    if k:
        tot += int(''.join(g))

Or in one line (as suggested in the comments down below):

tot = sum((int(''.join(g)) for k, g in groupby(s, str.isdigit) if k)
仅此而已 2025-01-05 11:38:26

编辑:我首先删除了这个答案,因为在这个线程中有更好的解决方案来解决你的问题,但是当你直接询问如何使用下一个方法来让你的代码工作时,我已经恢复了它,在如果您觉得它有用。

试试这个(为了方便起见,我模拟了迭代器):

def sort_by_type():
    maininput = iter("acdre2345ty")

    for char in maininput:
        if char.isalpha():
            print char
        elif char.isdigit():
            number = char
            while True:
                # try/except could take care of the StopIteration exception 
                # when a digit is last in the string
                #
                # try:
                #    char = maininput.next()
                # except StopIteration:
                #    char = ""
                #
                # however using next(iterator, default) is much better:
                #
                char = next(maininput, "")

                if char.isdigit():
                    number += char
                else:
                    break
            print number
            print char

如果产生:

a
c
d
r
e
2345
t
y

Edit: I first deleted this answer as there are much better solutions for your problem in this thread, but as you are directly asking how to use the next method to get your code working I have recovered it, in case you find it useful.

Try this (I mocked the iterator for convenience):

def sort_by_type():
    maininput = iter("acdre2345ty")

    for char in maininput:
        if char.isalpha():
            print char
        elif char.isdigit():
            number = char
            while True:
                # try/except could take care of the StopIteration exception 
                # when a digit is last in the string
                #
                # try:
                #    char = maininput.next()
                # except StopIteration:
                #    char = ""
                #
                # however using next(iterator, default) is much better:
                #
                char = next(maininput, "")

                if char.isdigit():
                    number += char
                else:
                    break
            print number
            print char

if produces:

a
c
d
r
e
2345
t
y
凹づ凸ル 2025-01-05 11:38:26

仅供娱乐(我无法抗拒,49 个字符):

eval(''.join([['+0+',x][x.isdigit()]for x in s]))

For entertainment purposes only (I couldn't resist, 49 chars):

eval(''.join([['+0+',x][x.isdigit()]for x in s]))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文