Python) Combing three textfiles(lists) into one with sorting
<p>I'm trying to make a new text file which is combined with 3 different text files. I'll give more detail with codes.</p>

<pre><code>text a file = z
              a
              y

text b file = s
              x
              d

text c file = 1
              3
              2
</code></pre>

<p>so there are a,b,c text files, and I want to make :</p>

<pre><code>text newfile: z s 1
              y d 2
              a x 3
</code></pre>

<p>As you can see above, I want newfile to be in order of 'C' file.
Below is what i've been made.</p>

<pre><code>def main():
a = open("text1","r")
b = open("text2","r")
c = open("text3","r")
text1list = []
text2list = []
text3list = []
for line1 in a:
    line1 = line1.strip()
    text1list.append(line1)
for line2 in b:
    line2 = line2.strip()
    text2list.append(line2)
for line3 in c:
    line3 = line3.strip()
    text3list.append(line3)
aa,bb,cc = zip(*sorted(zip(text3list, text1list, text2list)))
combine = list(zip(bb,cc,aa))
with open("finalfiles", 'w') as zzzz:
    for item in combine:
        zzzz.write("{}\n".format(item))
</code></pre>

<p>problem is, right now, my output is</p>

<pre><code>('z','s','1')
('y','d','2')
('a','x','3')
</code></pre>

<p>my sorting is working, but it's different from what I expect.
I don't want those ' ' and (). I think it's because those are lists...?
I'm stuck at this point.
Plus, please tell me my sorting looks fine !</p>

<p>Your <code>combine</code> variable is a list of tuples. Join each tuple (<code>item</code>) and write to file</p>

<pre><code>zzzz.write(" ".join(item))
</code></pre>

<p>A bit shorten and DRY version of your code:</p>

<pre><code>files = ["text1", "text2", "text3"]
groups = []
for each_file in files:
    with open(each_file, 'r') as fo:
        groups.append(sorted(fo.read().split('\n')))
with open("finalfiles", 'w') as out_file:
    for each_group in zip(*groups):
        out_file.write("{} {} {}\n".format(*each_group))
</code></pre>

python