Beispiel #1
0
    def group_by(self, grouping_f):
        """
        Group items by ``grouping_f``.

        >>> foods = Linq([
        ...     {'name': 'tomato', 'kind': 'Vegetable'},
        ...     {'name': 'hormone', 'kind': 'Meat'},
        ...     {'name': 'butdock root', 'kind': 'Vegetable'},
        ...     {'name': 'pumpkin', 'kind': 'Vegetable'}
        ... ])
        >>> foods.group_by(lambda f: f['kind'])
        IGroup<
            {Vegetable:
                Linq<{'name': 'tomato', 'kind': 'Vegetable'},
                {'name': 'butdock root', 'kind': 'Vegetable'},
                {'name': 'pumpkin', 'kind': 'Vegetable'}>},
            {Meat:
                Linq<{'name': 'hormone', 'kind': 'Meat'}>}
        >
        """
        from ilinq.igroup import IPair, IGroup
        group_dict = defaultdict(lambda: Linq([]))
        for item in self[:]:
            group_dict[grouping_f(item)].append(item)

        return IGroup([IPair(*pair) for pair in group_dict.items()])
Beispiel #2
0
 def test_str(self):
     group = IGroup([IPair(0, Linq([0, 1, 2])), IPair(1, Linq([0, 1, 3]))])
     assert_equal(str(group),
                  'IGroup<{0: Linq<0, 1, 2>}, {1: Linq<0, 1, 3>}>')
Beispiel #3
0
 def test_values(self):
     group = IGroup([IPair(0, Linq([0, 1, 2])), IPair(1, Linq([0, 1, 3]))])
     assert_equal(group.values, [Linq([0, 1, 2]), Linq([0, 1, 3])])
Beispiel #4
0
 def test_keys2(self):
     group = IGroup([IPair(0, Linq([0, 1, 2])), IPair(1, Linq([0, 1, 3]))])
     assert_equal(group.keys, [0, 1])
Beispiel #5
0
 def test_init4(self):
     IGroup([
         IPair(0, Linq([1, 2, 3])),
         IPair(1, Linq([2, 3, 4])),
         IPair(1, Linq([2, 3, 4]))
     ])
Beispiel #6
0
 def test_init3(self):
     IGroup([0, IPair(1, Linq([1, 2, 3]))])
Beispiel #7
0
 def test_init2(self):
     IGroup([IPair(0, Linq([0, 1, 2]))])
Beispiel #8
0
 def test_init(self):
     assert_equal(IGroup().count(), 0)
Beispiel #9
0
 def test_group_by(self):
     linq = Linq(range(6))
     assert_equal(
         linq.group_by(lambda n: n % 2),
         IGroup([IPair(0, Linq([0, 2, 4])),
                 IPair(1, Linq([1, 3, 5]))]))