title: Python Nested List Comprehension with If Else
body: <p>I was trying to use a list comprehension to replace multiple possible string values in a list of values.</p>
  
  <p>I have a list of column names which are taken from a <code>cursor.description</code>;</p>
  
  <pre><code>['UNIX_Time', 'col1_MCA', 'col2_MCA', 'col3_MCA', 'col1_MCB', 'col2_MCB', 'col3_MCB']
  </code></pre>
  
  <p>I then have <code>header_replace</code>;</p>
  
  <pre><code>{'MCB': 'SourceA', 'MCA': 'SourceB'}
  </code></pre>
  
  <p>I would like to replace the string values for <code>header_replace.keys()</code> found within the column names with the values.</p>
  
  <p>I have had to use the following loop;</p>
  
  <pre><code>headers = []
  for header in cursor.description:
      replaced = False
      for key in header_replace.keys():
          if key in header[0]:
              headers.append(str.replace(header[0], key, header_replace[key]))
              replaced = True
              break
  
      if not replaced:
          headers.append(header[0])
  </code></pre>
  
  <p>Which gives me the correct output;</p>
  
  <pre><code>['UNIX_Time', 'col1_SourceA', 'col2_SourceA', 'col3_SourceA', 'col1_SourceB', 'col2_SourceB', 'col3_SourceB']
  </code></pre>
  
  <p>I tried using this list comprehension;</p>
  
  <pre><code>[str.replace(i[0],k,header_replace[k]) if k in i[0] else i[0] for k in header_replace.keys() for i in cursor.description]
  </code></pre>
  
  <p>But it meant that items were duplicated for the unmatched keys and I would get;</p>
  
  <pre><code>['UNIX_Time', 'col1_MCA', 'col2_MCA', 'col3_MCA', 'col1_SourceA', 'col2_SourceA', 'col3_SourceA', 
  'UNIX_Time', 'col1_SourceB', 'col2_SourceB', 'col3_SourceB', 'col1_MCB', 'col2_MCB', 'col3_MCB']
  </code></pre>
  
  <p>But if instead I use;</p>
  
  <pre><code>[str.replace(i[0],k,header_replace[k]) for k in header_replace.keys() for i in cursor.description if k in i[0]]
  </code></pre>
  
  <p><em>@Bakuriu fixed syntax</em></p>
  
  <p>I would get the correct replacement but then loose any items that didn't need to have an string replacement.</p>
  
  <pre><code>['col1_SourceA', 'col2_SourceA', 'col3_SourceA', 'col1_SourceB', 'col2_SourceB', 'col3_SourceB']
  </code></pre>
  
  <p>Is there a pythonesque way of doing this or am I over stretching list comprehensions? I certainly find them hard to read.</p>