大家晚上好,我想知道有更快的方法来生成以下表格的列表吗?
[a,b,c,…,z] → [[z], [y,z], [x,y,z], … , [a,b,…,y,z]]
我知道切片是最好的方法之一,但不是更快的方法吗?
这就是我所拥有的:
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:])
我的回答:
['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']
没有错误
答案 0 :(得分:4)
类似的东西:
>>> 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']
...
或者(避免使用range
和len
):
for test in (lower[-i:] for i, j in enumerate(lower, start=1)):
print test
答案 1 :(得分:2)
是的,可能您正在寻找
>>> 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'],
答案 2 :(得分:2)
检查这个
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'], ....
答案 3 :(得分:1)
string.ascii_lowercase
返回小写字母'abcdefghijklmnopqrstuvwxyz'。此值不依赖于语言环境,不会更改。这比写出每一封信都容易:)
import string
alphabet = string.ascii_lowercase
for i in range(1, len(alphabet) + 1):
print list(alphabet[-i:])