![](/img/trans.png)
[英]how do you remove the nth item in a list until only one element is left in the list in python
[英]How do you remove the nth index of a nested list?
在那上面我經常撓頭。
我有以下格式的嵌套列表:
( (value1, value2, value3), (value1, value2, value3), ... (value1, value2, value3))
現在,我試圖將其歸結為:
( (value1, value2), (value1, value2), ... (value1, value2))
簡而言之,嘗試刪除每個嵌套列表的第三個元素。
在Python中這可能直接嗎?
您可以簡單地通過列表理解來做到這一點:
>>> x = [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
>>> x = [(a, b) for (a, b, c) in x]
[(1, 2), (1, 2), (1, 2)]
使用列表理解:
outerlist = [sublist[:-1] for sublist in outerlist]
這使用切片來刪除每個包含的子列表的最后一個元素。
上面創建了一個list()
,而不是一個tuple()
; 以下將再次創建一個元組:
outertuple = tuple(sublist[:-1] for sublist in outertuple)
切片子列表所需的操作碼比解壓縮和重新打包元組要少,從而更快地將結果提供給您。
使用元組的演示:
>>> outertuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
>>> tuple(sublist[:-1] for sublist in outertuple)
((1, 2), (4, 5), (7, 8))
演示使用列表:
>>> outerlist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [sublist[:-1] for sublist in outerlist]
[[1, 2], [4, 5], [7, 8]]
最后但並非最不重要的一點是,列表理解的內部循環的字節碼分解表明,切片使用的操作碼少於解壓縮和重新打包的次數:
>>> import dis
>>> def foo(x): return [sublist[:-1] for sublist in x]
...
>>> def bar(x): return [(a, b) for (a, b, c) in x]
...
>>> dis.dis(foo)
1 0 BUILD_LIST 0
3 LOAD_FAST 0 (x)
6 GET_ITER
>> 7 FOR_ITER 16 (to 26)
10 STORE_FAST 1 (sublist)
13 LOAD_FAST 1 (sublist)
16 LOAD_CONST 1 (-1)
19 SLICE+2
20 LIST_APPEND 2
23 JUMP_ABSOLUTE 7
>> 26 RETURN_VALUE
>>> dis.dis(bar)
1 0 BUILD_LIST 0
3 LOAD_FAST 0 (x)
6 GET_ITER
>> 7 FOR_ITER 27 (to 37)
10 UNPACK_SEQUENCE 3
13 STORE_FAST 1 (a)
16 STORE_FAST 2 (b)
19 STORE_FAST 3 (c)
22 LOAD_FAST 1 (a)
25 LOAD_FAST 2 (b)
28 BUILD_TUPLE 2
31 LIST_APPEND 2
34 JUMP_ABSOLUTE 7
>> 37 RETURN_VALUE
11對14操作碼。 與SLICE+2
相比,這是一個額外的UNPACK_SEQUENCE
和另外兩個STORE_FAST
操作碼,以及一個BUILD_TUPLE
操作碼。
這些差異使拆包和打包速度大大降低:
>>> import timeit
>>> test = [(42, 69, 180) for _ in xrange(1000)]
>>> timeit.timeit('f(x)', 'from __main__ import test as x, foo as f', number=10000)
1.1722910404205322
>>> timeit.timeit('f(x)', 'from __main__ import test as x, bar as f', number=10000)
1.6375460624694824
>>> a = ((1,2,3), (4,5,6), (7,8,9))
>>> a = tuple([(x1, x2) for (x1, x2, x3) in a])
>>> a
((1, 2), (4, 5), (7, 8))
nested_list= [[1,2,3],[4,5,6]]
for regular_list in nested_list:
del regular_list[2]
嘗試這個:
[a[ :-1] for a in b]
或這個:
[a[:n]+a[n+1:] for a in b]
使用地圖:
l = [[0,1,2], [1,2,3]]
print map(lambda l : l[:-1], l)
# Outputs [[0, 1], [1, 2]]
鑒於所有子列表的長度均為3。
如果您想要此元組:
l = ((0,1,2), (1,2,3))
print tuple(map(lambda l : l[:-1], l))
# Outputs ((0, 1), (1, 2))
x = [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
>>> [i[:2] for i in x ]
[(1、2),(1、2),(1、2)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.