社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中,从列表开始遍历逐渐变大的片段

timleathart • 5 年前 • 1365 次点击  

n 列表元素,来自 n = 1..N

lst = [1,2,3,4,5]

for n in range(1, len(lst)+1):
    print(lst[:n])

>>> [1]
>>> [1, 2]
>>> [1, 2, 3]
>>> [1, 2, 3, 4]
>>> [1, 2, 3, 4, 5]

foreach -设置此代码的样式版本,以避免稍微混淆 range(1, len(lst)+1)

for sublist in ___(lst):
    print(sublist)

我肯定有个好办法 itertools 或者什么,但我什么也找不到。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56508
 
1365 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Heap Overflow
Reply   •   1 楼
Heap Overflow    5 年前

我不认为你想要的形式有好的。你的方式已经很好了。我能想到的另一种方法是一次添加一个项目来构建它们。

prefix = []
for x in lst:
    prefix.append(x)
    print(prefix)