Ad
How To Add A Sublist To A Sublist?
I want to append a sublist to the previous sublist under certain circumstances, i.e. if its length is less than 2. So, the length of [5]
less than 2 and now the previous list is to be extended with the 5 (a+b).
a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]
L = [a,b,c,d,e,f]
print 'List:', L
def short(lists):
result = []
for value in lists:
if len(value) <= 2 and result:
result[-1] = result[-1] + value
return result
result = short(L)
print 'Result:', result
The result should be: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]
But from my code, I get: []
Ad
Answer
This might help
Ex:
a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]
L = [a,b,c,d,e,f]
print( 'List:', L)
def short(lists):
result = []
for value in lists:
if len(value) <= 2: #check len
result[-1].extend(value) #extend to previous list
else:
result.append(value) #append list.
return result
result = short(L)
print( 'Result:', result)
Output:
List: [[1, 1, 1, 1], [5], [1, 1, 1], [1, 1, 1, 1, 1], [1, 2], [1, 1, 1, 1, 1, 1]]
Result: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]
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