Saturday, 15 February 2014

python - pythonic way to combine a lot of startswith statements -


Begins with a lot of What is the "finer" way of combining statements?

Here are the details:
I receive various types of messages from a server, which send different letters to the recipients in order to quickly identify and sort them, A code is written with

  if message.startswith ('A'): do_A () elif message. Like statements, though, I think there is a more python way to write code without many statements, such as possibly all potential first letters Create a list and a  starts  statement. 

If the message [0] == 'A' is also better, otherwise it appears to be fast, and the speed matters to me. Use the first letter mapping for the

function:

  message_map = { 'A': do_A, 'B': do_B} dispatch = message_map.gate (message [: 1]) If there is no transmission: Send ()  

Functions in Python first class The objects are so that you can store them in a dictionary.

Note that I used one piece to get the first letter; messages will result in an empty string, instead of throwing an exception IndexError , instead of empty.


No comments:

Post a Comment