Returns a new PyQuery after transforming current items with func. func should take two arguments - 'index' and 'element'. Elements can also be referred to as 'this' inside of func:: >>> d = PyQuery(' Hi there Bye ') >>> d('p')
(self, func)
| 706 | return self |
| 707 | |
| 708 | def map(self, func): |
| 709 | """Returns a new PyQuery after transforming current items with func. |
| 710 | |
| 711 | func should take two arguments - 'index' and 'element'. Elements can |
| 712 | also be referred to as 'this' inside of func:: |
| 713 | |
| 714 | >>> d = PyQuery('<p class="hello">Hi there</p><p>Bye</p><br />') |
| 715 | >>> d('p').map(lambda i, e: PyQuery(e).text()) |
| 716 | ['Hi there', 'Bye'] |
| 717 | |
| 718 | >>> d('p').map(lambda i, e: len(PyQuery(this).text())) |
| 719 | [8, 3] |
| 720 | |
| 721 | >>> d('p').map(lambda i, e: PyQuery(this).text().split()) |
| 722 | ['Hi', 'there', 'Bye'] |
| 723 | |
| 724 | """ |
| 725 | items = [] |
| 726 | try: |
| 727 | for i, element in enumerate(self): |
| 728 | func.__globals__['this'] = element |
| 729 | result = callback(func, i, element) |
| 730 | if result is not None: |
| 731 | if not isinstance(result, list): |
| 732 | items.append(result) |
| 733 | else: |
| 734 | items.extend(result) |
| 735 | finally: |
| 736 | f_globals = func.__globals__ |
| 737 | if 'this' in f_globals: |
| 738 | del f_globals['this'] |
| 739 | return self._copy(items, parent=self) |
| 740 | |
| 741 | @property |
| 742 | def length(self): |