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

标签 python slice

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

[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/

相关文章:

python - 在 python 中使用 bson.json_util.loads 时如何忽略时区?

ruby - 如何在 Ruby 中随机取一段字符串?

python - 在 Python 中使用切片更改多个 Numpy 数组元素

JQuery Slice 添加类

Python pypyodbc 如何将变量插入到执行语句中?

python - 使用值而不是索引从 Python 列表中进行选择

python - 如何在 wxPython 中制作一个简单的文件浏览器?

string - 如何将 int slice 的字符串转换为 int slice ?

go - 获取字符串数组中每个字符串的第一个字符

python - 将稀疏数据输入到 Tensorflow Estimator 中进行拟合