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
194 views
in Technique[技术] by (71.8m points)

python - More pythonic way of item_list[-1] != item_list[-2]?

I'm updating and then referring to the last item added to a list to determine an outcome, for example:

if item_list[-1] != item_list[-2]:
   outcome1

I don't need to refer to any other list element, just item_list[-1] & [-2]. Is there a more pythonic way of doing this? This code is for on_message using websockets, and the item_list is being updated once per second or once per minute. Any advice would be appreciated by this novice coder!

question from:https://stackoverflow.com/questions/65878012/more-pythonic-way-of-item-list-1-item-list-2

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

1 Reply

0 votes
by (71.8m points)

You can use tricks like *rest, x, y = item_list and then compare, but I think your method is great.

Chasing a "more pythonic" method for something you already have a great method for, is sometimes unnecessary. I do however encourage and like your attempt at getting better. Keep it up!

And if your asking about efficiency - Your method is probably the best there is.


Per your pondering in the comments:

Just so you'll understand how fast it is, which is in the order of nanosecods and same speed no matter the length, here is a benchmark:

> py -m timeit -s "a = list(range(10_000))" "a[-1]"
2000000 loops, best of 5: 73.3 nsec per loop

> py -m timeit -s "a = list(range(100_000))" "a[-1]"
5000000 loops, best of 5: 74.5 nsec per loop

> py -m timeit -s "a = list(range(1_000_000))" "a[-1]"
5000000 loops, best of 5: 69.6 nsec per loop

More than 10 billion lookups per second (on my old computer from 2009) is fast enough I think ;-)


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

...