2

I want to read two unequal size python lists and write to the files. I can do this by repeating for-loops

with open(folder/'{}_matched_1_ids.txt'.format(f_1_latest[7:11]), 'a+') as matched_1_IDWriter, \
                        open(folder/'{}_matched_2_ids.txt'.format(f_1_latest[7:11]), 'a+') as matched_2_IDWriter:
   for item in matched_1:
      matched_1Writer.write("{},".format(item))
   for item in matched_2:
      matched_2Writer.write('{},'.format(item))

Instead of using 3 different for-loops, I could use itertools.zip_longest() with fillable option to none or "". But, I need nothing to fill (IGNORE) when loop's one iterator encounters nothing in the list to iterate over compared to other iterators. Is there a way to do that? I saw a similar pattern here but, didn't able to reproduce the solution in creating files.

Anu
  • 3,198
  • 5
  • 28
  • 49
  • So you want `zip_longest((1, 2), (3, 4, 5))` to return `[(1, 3), (2, 4), (5,)]` instead of `[(1, 3), (2, 4), (None, 5)]`? That just doesn't make any sense, since the last dangling item would not be placed correctly in the tuple if you don't fill the missing value with *something*. – blhsing Jul 17 '18 at 02:01
  • This really sounds like a job for two `for` loops to me. Mashing them together when there's no correspondence between the elements is pointless and confusing. – user2357112 Jul 17 '18 at 02:01
  • @Anubhav By the way, the SO question you link to does provide viable solutions to what you're asking for. Show us your implementation if you can't get any of them to work for you. – blhsing Jul 17 '18 at 02:12
  • Possible duplicate of [zip\_longest without fillvalue](https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue) – blhsing Jul 17 '18 at 02:15
  • @blhsing, I would like to mash for-loops into 1 so that I should not replicate the code multiple times. The [code](https://stackoverflow.com/questions/38054593/zip-longest-without-fillvalue) here help me to do it for lists but I am experiencing a hard time to reproduce it to get values in files. If I have to say 2k records in one list and 29K records in another list, the longest_zip() will fillvalue="" runs unnecessarily until 29kth iteration which I don't want. I was thinking a pythonic way of doing nothing when you encounter "none" or empty string in there. – Anu Jul 17 '18 at 11:13

0 Answers0