如何在指定索引之前和之后获取列表中的项目
问题描述:
假设我拥有列表f=[1,2,3]
和索引i
- 我想遍历f
,不包括i
。有没有一种方法可以使用i
来拆分清单,例如f[:i:]
,我将在i=1
中运行时给出一个新清单[1,3]
?我试图融入这个如何在指定索引之前和之后获取列表中的项目
代码:
# permutations, excluding self addition
# <something here> would be f excluding f[x]
f = [1,2,3]
r = [x + y for x in f for y in <something here>]
# Expected Output (notice absence of any f[i]+f[i])
[3, 4, 3, 5, 4, 5]
答
使用enumerate()
才能有在迭代时间访问索引。
[item for i, item in enumerate(f) if i != 3]
在这种情况下,你可以逃脱预期指数或者如果你有一组索引可以检查与in
的成员:
[item for i, item in enumerate(f) if i not in {3, 4, 5}]
如果你想在某个索引中删除项目通过删除项目
>>> l = ['a', 'b', 'c', 'd', 'e']
>>>
>>> del l[3]
>>> l
['a', 'b', 'c', 'e']
>>>
如果你想创建一个新的列表,并保留TEH主列表,你可以用一个简单的切片:你可以使用del
声明
>>> new = l[:3] + l[4:]
>>> new
['a', 'b', 'c', 'e']
答
迭代Ÿ在指数:
f = [10,20,30,40,50,60]
r = [x + f[y] for x in f for y in range(len(f)) if f[y] != x]
答
可能不是最完美的解决方案,但是这可能工作:
f = [1,2,3,4,5]
for i, x in enumerate(f):
if i == 0:
new_list = f[1:]
elif i == len(f) -1:
new_list = f[:-1]
else:
new_list = f[:i]+f[i+1:]
print i, new_list
打印:
0 [2, 3, 4, 5]
1 [1, 3, 4, 5]
2 [1, 2, 4, 5]
3 [1, 2, 3, 5]
4 [1, 2, 3, 4]
答
那么,它可能看起来吓人,但那是一个一行,做的工作:
>>> from numpy import array
>>> import itertools
>>> list(itertools.chain(*(i+array(l) for i,l in zip(reversed(f), itertools.combinations(f, len(f)-1)))))
[3, 4, 3, 5, 4, 5]
如果你看它慢慢地,它没有那么复杂:
-
的
itertools.combination
给所有可能的选项给len(f)-1
组合:>>> list(itertools.combinations(f, len(f)-1)) [(1, 2), (1, 3), (2, 3)]
-
你跟
zip
和reversed(f)
包裹它,就可以得到每个组合在一起与缺失值:>>> [(i,l) for i,l in zip(reversed(f), itertools.combinations(f, len(f)-1))] [(3, (1, 2)), (2, (1, 3)), (1, (2, 3))]
-
然后你转换
l
到numpy.array
这样你就可以添加缺少的值:>>> list((i+array(l) for i,l in zip(reversed(f), itertools.combinations(f, len(f)-1)))) [array([4, 5]), array([3, 5]), array([3, 4])]
而且finaly您使用
itertools.chain
获得期望的结果。
是'f = [10,20,30,40,50,60]; ind = 3; f_new = f [:ind] + f [ind + 1:];打印(f_new);'你的意思是自我添加? – mitoRibo
我已经更新了我的问题的清晰度 – MrDuk
@MrDuk ...所以,你试图遍历一个列表,并在每次迭代创建一个新的列表,排除当前的索引?从你的问题来看,你试图达到的目标并不是很清楚。 – tamjd1