Python列表理解是否可以访问索引/枚举? [英] is Python list comprehension with access to the index/enumerate possible?

查看:167
本文介绍了Python列表理解是否可以访问索引/枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Python代码,我在新的list2中添加所有项目,索引从list1的1到3:

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)

如果我有,你会怎么用python list comprehension写这个无法通过枚举访问索引?

how would you write this using python 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆