Aug-13-2020, 07:37 PM
Below is a test program to illustrate what I want to achieve. It is done using several for loops with intermediate variables.
Is there a way to combine these operations into one or two lines using list comprehension in some way? I have not been able to work out how to do this, so I would appreciate any advice you can provide.
Peter
Is there a way to combine these operations into one or two lines using list comprehension in some way? I have not been able to work out how to do this, so I would appreciate any advice you can provide.
Peter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Input lists l1 = [ "abc\ndef\nghi\n" , "jkl\nmno\npqr\n" ] l2 = [ "123\n456\n789\n" , "987\n654\n321\n" ] # Desired result list lwant = [ "abc|123\ndef|456\nghi|789\n" , "jkl|987\nmno|654\npqr|321\n" ] print ( "from:\n" , l1, "\n" , l2, "\nwant:\n" , lwant, "\n" ) l1s = [] l2s = [] for ln in range ( len (l1)): l1s.append([]) l1s[ln] = l1[ln].splitlines() l2s.append([]) l2s[ln] = l2[ln].splitlines() print ( "after splitlines:\n" , l1s, "len(l1s)=%d,len(l1s[0])=%d\n" % ( len (l1s), len (l1s[ 0 ])), l2s, "len(l2s)=%d,len(l2s[0])=%d\n" % ( len (l2s), len (l2s[ 0 ]))) lcomb = [] for ln in range ( len (l1)): lcomb.append([]) for sn in range ( len (l1s[ 0 ])): lcomb[ln].append([]) lcomb[ln][sn] = l1s[ln][sn] + "|" + l2s[ln][sn] + "\n" print ( "after combining:\n%s" % lcomb, "\n" ) ljoin = [] for ln in range ( len (lcomb)): ljoin.append("") ljoin[ln] = "".join(lcomb[ln]) print ( "after join:\n" , ljoin) |
Output:from:
['abc\ndef\nghi\n', 'jkl\nmno\npqr\n']
['123\n456\n789\n', '987\n654\n321\n']
want:
['abc|123\ndef|456\nghi|789\n', 'jkl|987\nmno|654\npqr|321\n']
after splitlines:
[['abc', 'def', 'ghi'], ['jkl', 'mno', 'pqr']] len(l1s)=2,len(l1s[0])=3
[['123', '456', '789'], ['987', '654', '321']] len(l2s)=2,len(l2s[0])=3
after combining:
[['abc|123\n', 'def|456\n', 'ghi|789\n'], ['jkl|987\n', 'mno|654\n', 'pqr|321\n']]
after join:
['abc|123\ndef|456\nghi|789\n', 'jkl|987\nmno|654\npqr|321\n']