Conditionally Merging list of lists with rows of a text file
<p>Consider these two data structures:</p>

<pre><code>var_a = [['apple','fruit','1'],['banana', 'fruit', '2'],['orange', 'fruit', '3']]
</code></pre>

<p>text file contents:</p>

<pre><code>'1', '20,000', 'USA'
'2', '45,000', 'Russia'
'3', '56,000', 'China'
</code></pre>

<p>I want to use a list comprehension that will give me an output as follows:</p>

<pre><code>'Apple', '1', '20,000', 'USA'
'Banana', '2', '45,000', 'Russia'
'Orange', '3', '56,000', 'China'
</code></pre>

<p>The code I have tried so far is:</p>

<pre><code>import json

file = open(name, 'r') #read in rows of data from text file
file_rows = file.read()

file_rows = file_rows.split('\n')

for x_file in file_rows:

    x_file2 = x_file.split(',')

    my_text_file = open(text_file_path, 'r')
    var_a = my_text_file.read() #read in list of lists from text file

    the_list = json.loads(var_a.replace("'", '"'))

    if any(x_file2[0] == x[2] for x in the_list) == True:

    print xfile2[0], x
</code></pre>

<p>I'm still a bit out there from what I am after. Can someone tell me how I should amend the list comprehension to achieve the desired output?</p>

<p>Thanks</p>

<p>Below is the sample code for list comprehension with the use of <code>itertools</code>:</p>

<pre><code>import itertools

with open('/tmp/my_text_file.txt') as f:
    new_list = [list(itertools.chain(item[1][:1], item[0].strip().replace("'", "").split(", "))) for item in zip(f.readlines(), var_a)]

# new_list = [['apple', '1', '20,000', 'USA'], ['banana', '2', '45,000', 'Russia'], ['orange', '3', '56,000', 'China']]
</code></pre>

python json list-comprehension