Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is not a csv problem, since you don't have a csv. (In fact you confused me for some time because I was trying to imagine what the csv file looked like!)</p> <ol> <li>Establish a "test" of whether a list needs normalization (<code>is_tuple_string_row</code> function below).</li> <li>Use <a href="http://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> to safely convert the string-of-tuple into an actual tuple.</li> <li>Use <a href="http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>chain.from_iterable</code></a> to combine all the tuples into a single sequence.</li> </ol> <p>Full code below implemented as the generator <code>normalized_list()</code>.</p> <pre><code>l = [["('N', '', 'SHOWERS', '', 'RD', '11734', '11734', '', '')", "('61060', '61060')"], ['', '', 'NORA', '', 'RD', '10301', '10999', '10400', '10998', '61089', '61089']] l2 = [['N', '', 'SHOWERS', '', 'RD', '11734', '11734', '', '', '61060', '61060'], ['', '', 'NORA', '', 'RD', '10301', '10999', '10400', '10998', '61089', '61089']] import ast from itertools import imap, chain def is_tuple_string_row(L): """Return whether list L is a list of strings containing tuples""" return len(L)==2 and all(s.startswith("('") and s.endswith("')") for s in L) def normalized_list(L): """Yield lists in sequence L as lists of strings Normalizes a list of strings of tuples down to a simple list of strings """ for item in L: if is_tuple_string_row(item): yield list(chain.from_iterable(imap(ast.literal_eval, item))) else: yield item # You can iterate efficiently for item in normalized_list(l): print item # or you can put the whole thing to a single new list aslist = list(normalized_list(l)) # verify results assert aslist == l2 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload