Python 迭代器行为
给定一个任意输入字符串,我的目的是找到该字符串中所有数字的总和。 这显然要求我在迭代字符串时知道字符串中的下一个元素......并决定它是否是整数。如果前一个元素也是整数,则这两个元素形成一个新整数,所有其他字符都将被忽略,依此类推。
例如,输入字符串
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 字符串已经是可迭代的,无需创建自己的迭代器。
因此,您想要的东西可以在没有迭代器的情况下简单地实现:
这会导致:
Python strings are already iterable, no need to create you own iterator.
What you want is thus simply achieved without iterators:
Which results in:
这可以通过
itertools.groupby
:或者在一行中(按照下面评论中的建议):
This can be done with
itertools.groupby
:Or in one line (as suggested in the comments down below):
编辑:我首先删除了这个答案,因为在这个线程中有更好的解决方案来解决你的问题,但是当你直接询问如何使用下一个方法来让你的代码工作时,我已经恢复了它,在如果您觉得它有用。
试试这个(为了方便起见,我模拟了迭代器):
如果产生:
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):
if produces:
仅供娱乐(我无法抗拒,49 个字符):
For entertainment purposes only (I couldn't resist, 49 chars):