Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing: Generates a list of lists [a,b,c,...z] = [z], [y,z]

Tags:

python

slice

Good evening everyone I was wondering it there a faster way to generate a list in the following form?

[a,b,c,…,z] → [[z], [y,z], [x,y,z], … , [a,b,…,y,z]]

I know that slicing is one of the best methods but isn't there faster way?

here is what I have:

import string

a = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
     's','t','u','v','w','x','y','z']


print (a, "\n",a[:24:-1], "\n",a[24:], a[23:] , a[22:], 
       a[21:], a[20:], a[19:], a[18:]) 

My answer:

['z'] 
['y', 'z'] 
['x', 'y', 'z'] 
['w', 'x', 'y', 'z']
['v', 'w', 'x', 'y', 'z'] 
['u', 'v', 'w', 'x', 'y', 'z'] 
['t', 'u', 'v', 'w', 'x', 'y', 'z'] 
['s', 't', 'u', 'v', 'w', 'x', 'y', 'z']

no errors

like image 900
Thomas Jones Avatar asked Nov 30 '25 16:11

Thomas Jones


2 Answers

Something like:

>>> from string import ascii_lowercase
>>> lower = list(ascii_lowercase)
>>> for i in range(1, len(lower) + 1):
    print lower[-i:]


['z']
['y', 'z']
['x', 'y', 'z']
['w', 'x', 'y', 'z']
['v', 'w', 'x', 'y', 'z']
...

Alternatively (avoiding using range and len):

for test in (lower[-i:] for i, j in enumerate(lower, start=1)):
    print test
like image 112
Jon Clements Avatar answered Dec 02 '25 07:12

Jon Clements


check this

In[9] : [st[-i:] for i in range(1, len(st)+1)]
Out[9]: [['z'],
['y', 'z'],
['x', 'y', 'z'],
['w', 'x', 'y', 'z'],
['v', 'w', 'x', 'y', 'z'],
['u', 'v', 'w', 'x', 'y', 'z'],
['t', 'u', 'v', 'w', 'x', 'y', 'z'],
['s', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], ....
like image 33
avasal Avatar answered Dec 02 '25 07:12

avasal