Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python - Cleaner way to Pop item in list of list

I have a list of lists:

a = [[1,2,'a','b'],[3,4,'c','d'],[5,6,'e','f']]

and I want the result:

[[1,2],[3,4],[5,6]]
and
[['a','b'],['c','d'],['e','f']]

I can do it with a loop and pop but am wondering if there's a better way using slicing or a cleaner method:

d = []
for i in a:
    b = i.pop()
    c = i.pop()
    d.append([c,b])

In: a                                                                                                                                                                                                         
Out: [[1, 2], [3, 4], [5, 6]]

In: d                                                                                                                                                                                                         
Out: [['a', 'b'], ['c', 'd'], ['e', 'f']]

question from:https://stackoverflow.com/questions/65947887/cleaner-way-to-pop-item-in-list-of-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately, there is no way other than iterating over the list of lists.

x,y = [i[:2] for i in a], [i[2:] for i in a]
print(x)
print(y)

[[1, 2], [3, 4], [5, 6]]
[['a', 'b'], ['c', 'd'], ['e', 'f']]

If you are open to using numpy then -

import numpy as np

x,y = np.array(a)[:,:2], np.array(a)[:,2:]
print(x)
print(y)
[['1' '2']
 ['3' '4']
 ['5' '6']]

[['a' 'b']
 ['c' 'd']
 ['e' 'f']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...