Create constants for offsets into a list
I have a list similar to this:
host_info = ['stackoverflow.com', '213.213.214.213', 'comments', 'desriprion', 'age']
Sometimes, I need to remove one or more elements from the list and then return the list to the caller开发者_运维百科. To remove the comments item as an example I'd do this:
host_info.pop(2)
I'd prefer to use a constant for each item rather than some magic number.
Then I could use:
host_info.pop(comments) # comments is integer 2
What's the best way to enumerate these constants so it's simple to maintain them when the list offsets change?
The easiest approach would be to change your list to a dictionary:
keys_list = ['host',...]
host_info = dict(zip(['stackoverflow.com', '213.213.214.213', 'comments', 'desriprion', 'age'], keys_list))
Now you don't have to worry about the key list and if you remove an item from the host_info dictionary it won't affect the key => value associations
or if you only have one host info list:
host_info = {'host':'stackoverflow.com, 'ip':'213.213.214.213',...}
EDIT:
To remove a key from the host_info use pop
:
host_info.pop('host')
If you aren't sure the key is there you can use:
host_info.pop('host',None)
or you can use:
if 'host' in host_info:
del host_info['host']
As a side note AdamKG has a nice comment explaining that you wouldn't want to convert this back to a list. You could instead do this:
host = host_info['host']
This removes the dependence on a "key" mapping list and combines the two lists into a single associative container.
精彩评论