Call compression of the "n" -time member

Is there any implicit way to forcall member ntimes for an object?

I was thinking of some kind of approach map/reduce/lambda, but I could not figure out how to do it - if possible.

Just to add context, I use BeautifulSoupand I extract some elements from the html table; I extract some elements, and then, the last one.

Since I have:

# First value
print value.text

# Second value
value = value.nextSibling
print value.text

# Ninth value
for i in xrange(1, 7):
    value = value.nextSibling
print value.text

I was wondering if there was any approach lambda- or something else - that would allow me to do this:

# Ninth value
((value = value.nextSibling) for i in xrange(1, 7))
print value.text

PS: No, there is no problem with the approach for, except that I really like single-line solutions, and it will be very convenient in my code.

+3
source share
6

, reduce:

>>> class Foo(object):
...     def __init__(self):
...        self.count = 0
...     def callme(self):
...        self.count += 1
...        return self
... 
>>> a = Foo()
>>> reduce(lambda x,y:x.callme(),range(7),a)
<__main__.Foo object at 0xec390>
>>> a.count
7
+7

:

for i in xrange(1, 7):
    value = value.nextSibling

:

for i in xrange(1, 7): value = value.nextSibling

- , compose, callme() ( attrgetter('my_prop'), - ) 7 .

+4

BS nextSiblingGenerator() itertools.islice, n- . , n- .

from itertools import islice

nth = 7
next(islice(elem.nextSiblingGenerator(), nth, None), None)
+2

: eval - .

value = eval('value' + ('.nextSibling' * 7))
+2

! reduce Python3, , .

, , Python2/3 OP:

[globals().update(value=value.nextSibling) for i in range(7)]

, value . -, :

[self.__dict__.update(value=value.nextSibling) for i in range(7)]

locals(), , locals() . :

(lambda loc : [loc.update(x=x.nextSibling) for i in range(7)])(locals())

, :

loc = locals()
[loc.update(value=value.nextSibling) for i in range(7)]

, :

loc = locals() ; [loc.update(value=value.nextSibling) for i in range(7)]

, Python ; 8 -)

UPDATE

, map :

list(map(lambda d : d.update(value=value.nextSibling), 7 * [locals()]))

locals() .

+1

:

value = reduce(lambda x, _: x.nextSibling, xrange(1,7), value)
+1

All Articles