gpt4 book ai didi

python - 切片 : Generates a list of lists [a, b,c,...z] = [z], [y,z]

转载 作者:行者123 更新时间:2023-11-28 20:08:02 28 4
gpt4 key购买 nike

大家晚上好我想知道有没有更快的方法来生成以下形式的列表?

[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']

没有错误

最佳答案

类似于:

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

或者(避免使用 rangelen):

for test in (lower[-i:] for i, j in enumerate(lower, start=1)):
print test

关于python - 切片 : Generates a list of lists [a, b,c,...z] = [z], [y,z],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15150566/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com