Python Forum
How to split and combine embedded lines using less code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to split and combine embedded lines using less code
#1
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

# 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']
Reply
#2
spam = ["abc\ndef\nghi\n", "jkl\nmno\npqr\n"]
eggs = ["123\n456\n789\n", "987\n654\n321\n"]

result = []
for chars, nums in zip(spam, eggs):
    element = '\n'.join('|'.join(item) for item in zip(chars.strip().split('\n'), nums.strip().split('\n')))
    result.append(f'{element}\n')
print(result)
Output:
['abc|123\ndef|456\nghi|789\n', 'jkl|987\nmno|654\npqr|321\n']
of course line 6 is ugly and probably should be split in multiple lines, e.g. lines 5-7 above will become

for chars, nums in zip(spam, eggs):
    chars = chars.strip().split('\n')
    nums = nums.strip().split('\n')
    element = '\n'.join('|'.join(item) for item in zip(chars, nums))
    result.append(f'{element}\n')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks much for the prompt reply. One question: Why strip().split("\n") instead of just splitlines()?

Peter
Reply
#4
(Aug-13-2020, 08:14 PM)pjfarley3 Wrote: Why strip().split("\n") instead of just splitlines()?
no reason - it's perfectly fine to use splitlines() instead
it was easier to do the steps one by one - strip the trailining new line, split at '\n'

spam = ["abc\ndef\nghi\n", "jkl\nmno\npqr\n"]
eggs = ["123\n456\n789\n", "987\n654\n321\n"]

result = []
for chars, nums in zip(spam, eggs):
    element = '\n'.join('|'.join(item) for item in zip(chars.splitlines(), nums.splitlines()))
    result.append(f'{element}\n')
print(result)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Thanks again, that at least shows me I understand the process.

Is it possible to solve this in python V2.7? As I understand it f-strings are V3.6+ specific, correct?

Peter
Reply
#6
f-strings are 3.6+
earlier versions, incl. 2.7
result.append('{}\n'.format(element))
but you shouldn't be using 2.7/ python2 support has ended
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thank you again for your prompt and precise answers.

I will mark this one solved.

Peter
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python seems to be skipping lines of code alansandbucket 1 448 Jun-22-2021, 01:18 AM
Last Post: Larz60+
  [split] Kera Getting errors when following code example Image classification from scratch hobbyist 3 2,028 Apr-13-2021, 01:26 PM
Last Post: amirian
  Running a few lines of code as soon as my timer ends nethatar 3 641 Feb-26-2021, 01:02 PM
Last Post: jefsummers
  Assistance with running a few lines of code at an EXACT time nethatar 5 823 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Making new lines of code AvioxyYT 1 516 Jan-22-2021, 07:02 PM
Last Post: buran
  Split Characters As Lines in File quest_ 3 810 Dec-28-2020, 09:31 AM
Last Post: quest_
  Repeating lines of code by an input Josh_Albanos 3 891 Oct-15-2020, 01:04 AM
Last Post: deanhystad
  [split] Python code help sairam17519 3 881 Sep-10-2020, 01:44 PM
Last Post: sairam17519
  Beginner: I need help understanding few lines of a code. hop_090 1 555 Sep-07-2020, 04:02 PM
Last Post: Larz60+
  How to Split Output Audio on Text to Speech Code Base12 2 3,625 Aug-29-2020, 03:23 AM
Last Post: Base12

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020