generator

Is there a generator version of `string.split()` in Python?

我是研究僧i 提交于 2020-01-25 08:15:08
问题 string.split() returns a list instance. Is there a version that returns a generator instead? Are there any reasons against having a generator version? 回答1: It is highly probable that re.finditer uses fairly minimal memory overhead. def split_iter(string): return (x.group(0) for x in re.finditer(r"[A-Za-z']+", string)) Demo: >>> list( split_iter("A programmer's RegEx test.") ) ['A', "programmer's", 'RegEx', 'test'] edit: I have just confirmed that this takes constant memory in python 3.2.1,

Is there a generator version of `string.split()` in Python?

你离开我真会死。 提交于 2020-01-25 08:15:05
问题 string.split() returns a list instance. Is there a version that returns a generator instead? Are there any reasons against having a generator version? 回答1: It is highly probable that re.finditer uses fairly minimal memory overhead. def split_iter(string): return (x.group(0) for x in re.finditer(r"[A-Za-z']+", string)) Demo: >>> list( split_iter("A programmer's RegEx test.") ) ['A', "programmer's", 'RegEx', 'test'] edit: I have just confirmed that this takes constant memory in python 3.2.1,

Control recursion on nested lists / strings (without checking for the type)

烈酒焚心 提交于 2020-01-25 08:05:33
问题 Assume I have the following input: items = [1, 2, [3, 4], (5, 6), 'ciao', range(3), (i for i in range(3, 6))] and I want to perform some recursive operation on items . For the sake of simplicity, let's say I want to flatten items (but could be anything else), one way of doing this would be: def flatten(items, max_depth=-1, shallow=(str, bytes, bytearray)): for item in items: if shallow and isinstance(item, shallow) or max_depth == 0: yield item else: try: for subitem in flatten(item, max

Decorating a generator in Python: call some method in between yields

ぐ巨炮叔叔 提交于 2020-01-24 10:12:06
问题 I found some very useful information about decorating generator functions in Python here using yield from . For example: def mydec(func): def wrapper(*args, **kwargs): print(f'Getting values from "{func.__name__}"...') x = yield from func(*args, **kwargs) print(f'Got value {x}') return x return wrapper @mydec def mygen(n): for i in range(n): yield i However, this seems to only allow for adding decorated behaviors at the beginning and end of the generator's lifetime: >>> foo = mygen(3) >>> x =

How to compare list values with dictionary keys and make a new dictionary of it using python

限于喜欢 提交于 2020-01-21 03:43:11
问题 I have a list like this: lis = ['Date', 'Product', 'Price'] I want to compare it with: dict = {'Date' : '2013-05-01', 'Salary' : '$5000', 'Product' : 'Toys', 'Price' : '$10', 'Salesman' : 'Smith'} I want to compare each item of list with keys of dictionary and make a new dictionary. What I have tried is: n = {} for k,v in dict.items(): for i in lis: if i==k: n[k] = v Output: n = {'Date' : '2013-05-01', 'Product' : 'Toys', 'Price' : '$10'} This works but I want to do it through generators -

Python 3.x: Test if generator has elements remaining

笑着哭i 提交于 2020-01-20 18:30:47
问题 When I use a generator in a for loop, it seems to "know", when there are no more elements yielded. Now, I have to use a generator WITHOUT a for loop, and use next () by hand, to get the next element. My problem is, how do I know, if there are no more elements? I know only: next () raises an exception (StopIteration), if there is nothing left, BUT isn't an exception a little bit too "heavy" for such a simple problem? Isn't there a method like has_next () or so? The following lines should make

How to make string primary key hibernate. @GeneratedValue strategies

ε祈祈猫儿з 提交于 2020-01-19 12:55:29
问题 My goal is to create an entity Device that has a unique field IMEI and I would like to use it as a primary key, and specify it at device registration time (manually specified, while creating the entity). I use Spring roo tool for development and hibernate as ORM. When I specify this in Entity declaration: @RooJavaBean @RooToString @RooJpaActiveRecord(identifierField = "IMEI", identifierType = String.class) public class Device {...} I get this generated: @Id @GeneratedValue(strategy =

What are some useful or interesting infinite generators? [closed]

烂漫一生 提交于 2020-01-17 06:54:37
问题 Closed . This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 4 years ago . What are some clever uses for infinite generators? I've seen lots of seemingly trivial examples like "list all even numbers" , but I assume there must be others that have more applicability to real-world scenarios. Concrete examples (in any language that support generators)

What are some useful or interesting infinite generators? [closed]

陌路散爱 提交于 2020-01-17 06:54:12
问题 Closed . This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 4 years ago . What are some clever uses for infinite generators? I've seen lots of seemingly trivial examples like "list all even numbers" , but I assume there must be others that have more applicability to real-world scenarios. Concrete examples (in any language that support generators)

Does this benchmark seem relevant?

萝らか妹 提交于 2020-01-16 18:41:18
问题 I am trying to benchmark a few method of itertools against generators and list comprehensions. The idea is that I want to build an iterator by filtering some entries from a base list. Here is the code I came up with(Edited after accepted answer): from itertools import ifilter import collections import random import os from timeit import Timer os.system('cls') # define large arrays listArrays = [xrange(100), xrange(1000), xrange(10000), xrange(100000)] #Number of element to be filtered out nb