[英]How to add element from last loop iteration to list in python?
我有这个清单:
t=['a','b','c']
并希望创建 output,例如:
['a']
['a','b']
['a','b','c']
我不确定如何调整此循环:
for i in t:
print(i)
我不确定如何编写循环以从上次迭代和当前迭代创建此附加效果。 我希望有人可以提供帮助。 谢谢。
没有嵌套循环的解决方案:
l = ['a','b','c']
res = []
temp = []
for item in l:
temp.append(item)
res.append(temp.copy())
print(res)
这应该是最简单的解决方案:
t=['a','b','c']
x=[]
for i in range(len(t)):
x.append(t[i])
print(x)
您可以使用生成器/列表理解,在打印切片索引并使用'\n'
作为分隔符时解压缩列表:
t = ['a','b','c']
print(*[t[:t.index(i)+1] for i in t], sep='\n')
要么:
for i in t:
print(t[:t.index(i)+1])
Output:
['a']
['a', 'b']
['a', 'b', 'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.