Best way to check list for specific items - python

I use try/except blocks as a replacement for if/elif , which has a bunch of and s. I am browsing the list and replacing some elements if it has x and x and x, etc. In my project, I have to check up on 6 things that attracted me to using try/except with .index() , which will throw an error if the element is missing.

The analogy looks like this:

 colors = ['red', 'blue', 'yellow', 'orange'] try: red_index = colors.index('red') blue_index = colors.index('blue') colors[red_index] = 'pink' colors[blue_index] = 'light blue' except ValueError: pass try: yellow_index = colors.index('yellow') purple_index = colors.index('purple') colors[yellow_index] = 'amarillo' colors[purple_index] = 'lavender' except ValueError: pass 

So, if the colors array does not contain 'purple' as well as 'yellow' , I do not want the array to change.

I am a little afraid of this approach, because it seems like abuse of try/except . But this is much shorter than the alternative, because in any case I would have to decorate the index elements, so I would like to know if there are glaring problems with this, or if it is so crazy that other developers hate me for it.

+6
source share
5 answers

This is not insanity; try / except is pretty pythonic - see this question for further discussion.

Another way you can do this:

 if 'red' in colours and 'blue' in colours: colour[colours.index('red')] = 'pink' # etc 

Advantages compared to try / except:

  • Fewer lines of code if you enter this
  • Much more readable - any future reader will immediately find out what you mean

Disadvantages over try / except:

  • Slower (although completely negligible), since contains will perform its own search for the element.

If you are not doing what requires it to be extremely time-efficient, I would favor readability. However, try / except is not unforgivable if you have other reasons for this.

+2
source

You can use set . We will use issuperset , difference_update and update , abbreviated >= , -= and |= respectively:

 colors = {'red', 'blue', 'yellow', 'orange'} if colors >= {'red', 'blue'}: colors -= {'red', 'blue'} colors |= {'pink', 'light blue'} elif colors >= {'yellow', 'purple'}: colors -= {'yellow', 'purple'} colors |= {'amarillo', 'lavender'} 
+2
source

Updated Answer

You probably want to build a function using map (), for example:

 def replace(sequence, replaceDict): for seekVal in replaceDict.keys(): if seekVal not in sequence: return sequence #Not modified, as seek not found. replaceFunc = lambda item: replaceVal if item==seekVal else item for seekVal in replaceDict: replaceVal = replaceDict[seekVal] sequence = map(replaceFunc, sequence) return sequence 

Then just run:

 colors = replace(colors, {'red' : 'pink', 'blue' : 'light blue'}) 
+1
source

Your code is close, but there are some useful built-in functions that will help:

 colors = ['red', 'blue', 'yellow', 'orange'] if ('red' in colors and 'blue' in colors): red_index = colors.index('red') blue_index = colors.index('blue') colors[red_index] = 'pink' colors[blue_index] = 'light blue' if ('yellow' in colors and 'purple' in colors): yellow_index = colors.index('yellow') purple_index = colors.index('purple') colors[yellow_index] = 'amarillo' colors[purple_index] = 'lavender' 

This creates a logical gate (both colors must be present) so that it is executed only when you want.

This is a very small change, but I think it will handle your mistakes better.

+1
source

You could go a simpler and much shorter way using a dict and list the understanding as follows:

 colors = ['red', 'blue', 'yellow', 'orange'] # First define you replaces replaces = { 'red': 'ping', 'blue': 'light blue', 'yellow': 'amarillo', 'purple': 'lavender' } # Then define the replacing function def replace(key, replaces): return replaces.get(key) or key # And then replace all the intended element colors = [replace(el, replaces) for el in colors] 

So, what will this do, for each element, it will look for it in the dict, if it is in the dict (i.e. intended for replacement), then it will return the corresponding replacement, otherwise it will return to its original value.

So, by entering your conditions, you can do the following:

 if 'purple' in colors and 'red' in colors: colors = [replace(el, { 'yellow': 'amarillo', 'purple': 'lavender' }) for el in colors] ... 

And the same for any other conditions.

+1
source

All Articles