Python迭代器问题
我有这个列表:
names = ['john','Jonh','james','James','Jardel']
我想循环列表并在同一迭代中处理具有不区分大小写匹配的连续名称。因此,在第一次迭代中,我会用“john”和“John”做一些事情,我希望下一次迭代从“james”开始。
我想不出一种使用 Python 的 for 循环来做到这一点的方法,有什么建议吗?
I have this list:
names = ['john','Jonh','james','James','Jardel']
I want loop over the list and handle consecutive names with a case insensitive match in the same iteration. So in the first iteration I would do something with'john' and 'John' and I want the next iteration to start at 'james'.
I can't think of a way to do this using Python's for loop, any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将是 itertools.groupby 的一个,它对列表或其他可迭代对象中的连续相等元素进行分组。您可以指定一个函数来进行比较,这样,在您的情况下,不同情况下的相同名称仍然可以算作同一件事。
This would be one for
itertools.groupby
, which groups consecutive equal elements from a list or other iterable. you can specify a function to do the comparison, so that, in your case, the same name in different cases can still be counted as the same thing.请注意,您需要均匀数量的物品才能正常工作。
或者(也许更好;很难在上下文中判断)使用
set
来过滤列表以仅包含唯一名称(请注意,这会丢失顺序):Note that you need an even amount of items for this to work properly.
Or (maybe better; hard to tell with little context) use a
set
to filter the list to contain only unique names (note that this loses order):您可以只使用
while
循环:或者您是否正在寻找更复杂的东西?
You could just use a
while
loop:Or are you looking for something a bit more involved?
当您迭代循环时,您可以尝试跟踪列表中的前一个名称。同时,当你要存储名称时,可以调用lower()或capitalize()来使每个名称的格式保持一致,以便于比较它们。
例如,
可能不是最有效的,但是有效。
As you iterate thru the loop, you could try keeping track of the previous name in the list. At the same time, when you're going to store the names, you can make a call to lower() or capitalize() to make the formatting of each name consistent so that you can compare them easier.
e.g.
May not be the most efficient, but works.
我的 0.02 美元:
我不确定我是否完全理解了这个问题;你想实现什么目标?
My $0.02:
I'm not sure I understood the question exactly; what are you trying to accomplish?