Ad
How To Split A Sorted List By Element Length
I have a list of lists and it is sorted by the length of the children lists. e.g.
[[str], [str1, str2], [str1, str2], [str1, str2, str3], [str1, str2, str3],...]
I would like to split this list into sublists that only contain the children with the same length. e.g.
[[[str], [str], [str]], [[str1, str2], [str1, str2], [str1, str2]], ...]
I was wondering if there is a more efficient approach than mine below with hopefully a little less code.
child_list = []
new_list = []
old_list = [['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010'],
['e3a0b000', 'e3a0e000'], ['e92d4030', 'e59f5054'],
['e59f3038', 'e3530000'], ['e1a0c00d', 'e92dd800']]
# length of child
length = 1
for idx, i in enumerate(old_list):
if idx == len(old_list)-1:
child_list.append(i)
new_list.append(child_list.copy())
elif length == len(i):
child_list.append(i)
elif length < len(i):
new_list.append(child_list.copy())
del child_list[:]
child_list.append(i)
length = len(i)
Output:
[[['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010']],
[['e3a0b000', 'e3a0e000'], ['e92d4030', 'e59f5054'],
['e59f3038', 'e3530000'], ['e1a0c00d', 'e92dd800']]]
Ad
Answer
You can use itertools.groupby
in order to group the lists in old
by length. Note that if the original lists are already ordered according to their length as in your example, sorting here is not necessary.
from itertools import groupby
[list(v) for k,v in groupby(sorted(old_list, key=len), key=len)]
Output
[[['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010']],
[['e3a0b000', 'e3a0e000'],
['e92d4030', 'e59f5054'],
['e59f3038', 'e3530000'],
['e1a0c00d', 'e92dd800']]]
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad