How does this Python code work to group a list by the first character of each element?
Question:
We weren’t taught how lambda works, so I was hoping to know how each line works in grouping list elements by each letter. (For example, test_list = [‘an’, ‘a’, ‘geek’, ‘for’, ‘g’, ‘free’], so the output becomes [[‘an’, ‘a’], [‘geek’, ‘g’], [‘for’, ‘free’]]). I’m also confused by the x[0] == y[0] part.
util_func = lambda x, y: x[0] == y[0]
res = []
for sub in test_list:
ele = next((x for x in res if util_func(sub, x[0])), [])
if ele == []:
res.append(ele)
ele.append(sub)
Answers:
The explanation of what lambda is doing in this case has been given in comments. However, it’s worth mentioning that the code shown in the question is extremely cumbersome. A dictionary solves this problem with ease and will almost certainly (I haven’t timed it) be much more efficient:
list_ = ['an', 'a', 'geek', 'for', 'g', 'free']
dict_ = {}
for e in list_:
dict_.setdefault(e[0], []).append(e)
print(list(dict_.values()))
Output:
[['an', 'a'], ['geek', 'g'], ['for', 'free']]
We weren’t taught how lambda works, so I was hoping to know how each line works in grouping list elements by each letter. (For example, test_list = [‘an’, ‘a’, ‘geek’, ‘for’, ‘g’, ‘free’], so the output becomes [[‘an’, ‘a’], [‘geek’, ‘g’], [‘for’, ‘free’]]). I’m also confused by the x[0] == y[0] part.
util_func = lambda x, y: x[0] == y[0]
res = []
for sub in test_list:
ele = next((x for x in res if util_func(sub, x[0])), [])
if ele == []:
res.append(ele)
ele.append(sub)
The explanation of what lambda is doing in this case has been given in comments. However, it’s worth mentioning that the code shown in the question is extremely cumbersome. A dictionary solves this problem with ease and will almost certainly (I haven’t timed it) be much more efficient:
list_ = ['an', 'a', 'geek', 'for', 'g', 'free']
dict_ = {}
for e in list_:
dict_.setdefault(e[0], []).append(e)
print(list(dict_.values()))
Output:
[['an', 'a'], ['geek', 'g'], ['for', 'free']]