Python:如何以列表理解格式扩展或追加多个元素? [英] Python: How to extend or append multiple elements in list comprehension format?
本文介绍了Python:如何以列表理解格式扩展或追加多个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对这段代码或类似的东西有一个整洁的列表理解!
I'd like to get a nice neat list comprehension for this code or something similar!
extra_indices = []
for i in range(len(indices)):
index = indices[i]
extra_indices.extend([index, index + 1, index +2])
谢谢!
编辑*索引是整数列表.另一个数组的索引列表.
Edit* The indices are a list of integers. A list of indexes of another array.
例如,如果索引为[1、52、150],则为目标(在这里,这是我第二次希望对列表理解中的连续索引输出执行两个单独的操作)
For example if indices is [1, 52, 150] then the goal (here, this is the second time I've wanted two separate actions on continuously indexed outputs in a list comprehension)
那么extra_indices将是[1、2、3、52、53、54、150、151、152]
Then extra_indices would be [1, 2, 3, 52, 53, 54, 150, 151, 152]
推荐答案
您可以在列表comp中使用两个循环-
You can use two loops in list comp -
extra_indices = [index+i for index in indices for i in range(3)]
这篇关于Python:如何以列表理解格式扩展或追加多个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文