Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Removing trailing empty elements in a list

Is there an elegant pythonic way of removing trailing empty elements from a list? A sort of list.rstrip(None). So

[1, 2, 3, None, 4, None, None]

should result in

[1, 2, 3, None, 4]

I guess this could be generalized to removing trailing elements of any particular value.

If possible, I would like to have this done as a single line (readable) expression

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you want to get rid of only None values and leave zeros or other falsy values, you could do:

while my_list and my_list[-1] is None:
    my_list.pop()

To remove all falsy values (zeros, empty strings, empty lists, etc.) you can do:

my_list = [1, 2, 3, None, 4, None, None]
while not my_list[-1]:
    my_list.pop()
print(my_list)
# [1, 2, 3, None, 4]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...