PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How does this Python code work to group a list by the first character of each element?

 November 04, 2022     lambda, python     No comments   

Issue

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)

Solution

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']]


Answered By - Cobra
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing