예제 #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()])
예제 #2
0
 def test_init(self):
     IPair(0, Linq([range(3)]))
예제 #3
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>}>')
예제 #4
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])])
예제 #5
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])
예제 #6
0
 def test_init4(self):
     IGroup([
         IPair(0, Linq([1, 2, 3])),
         IPair(1, Linq([2, 3, 4])),
         IPair(1, Linq([2, 3, 4]))
     ])
예제 #7
0
 def test_init3(self):
     IGroup([0, IPair(1, Linq([1, 2, 3]))])
예제 #8
0
 def test_init2(self):
     IGroup([IPair(0, Linq([0, 1, 2]))])
예제 #9
0
 def test_eq(self):
     assert_equal(IPair(0, Linq([0, 1])), IPair(0, Linq([0, 1])))
예제 #10
0
 def test_repr(self):
     assert_equal(repr(IPair(0, Linq([1]))), 'IPair{0: Linq<1>}')
예제 #11
0
 def test_str(self):
     assert_equal(str(IPair(0, Linq([1]))), '{0: Linq<1>}')
예제 #12
0
 def test_values(self):
     pair = IPair(0, Linq([1]))
     assert_equal(pair.values, Linq([1]))
예제 #13
0
 def test_key(self):
     pair = IPair(0, Linq([1]))
     assert_equal(pair.key, 0)
예제 #14
0
 def test_init2(self):
     IPair(0, 1)
예제 #15
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]))]))