简体   繁体   中英

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

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

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

Yes , probably you are looking for

>>> from string import ascii_lowercase
>>> import pprint
>>> from pprint import PrettyPrinter
>>> pp = PrettyPrinter(indent = 4,width = 255)
>>> pp.pprint([some_list[-i:] for i in range(1, len(ascii_lowercase) + 1)])
[   ['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'],

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

string.ascii_lowercase returns the lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change. This is easier than writing out every letter :)

import string

alphabet = string.ascii_lowercase
for i in range(1, len(alphabet) + 1):
    print list(alphabet[-i:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM