在Python列表理解中可以访问项目索引吗? [英] In Python list comprehension is it possible to access the item index?
本文介绍了在Python列表理解中可以访问项目索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下Python代码,我将新的 list2
中所有索引从1到3的项添加到新的 list2
中:
Consider the following Python code with which I add in a new list2
all the items with indices from 1 to 3 of list1
:
for ind, obj in enumerate(list1):
if 4 > ind > 0:
list2.append(obj)
如果我无法通过枚举访问索引,您将如何使用列表理解来编写此代码?
How would you write this using list comprehension, if I have no access to the indices through enumerate?
类似:
list2 = [x for x in list1 if 4 > ind > 0]
但是因为我没有 ind
号码,这行得通吗?
but since I have no ind
number, would this work?
list2 = [x for x in enumerate(list1) if 4 > ind > 0]
推荐答案
list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]
这篇关于在Python列表理解中可以访问项目索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文