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
  How to run detectron2, as python embedded code in C++, on GPU? hassaniqbal931 3 1,039 Nov-02-2023, 04:45 PM
Last Post: blabling2
  [split] Explain the python code in this definition Led_Zeppelin 1 711 Jan-13-2023, 10:20 PM
Last Post: deanhystad
  counting lines in split data Skaperen 6 1,348 Oct-07-2022, 07:09 PM
Last Post: Skaperen
  Regular Expression search to comment lines of code Gman2233 5 1,591 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  I want to simplify this python code into fewer lines, it's about string mandaxyz 5 2,045 Jan-15-2022, 01:28 PM
Last Post: mandaxyz
  python seems to be skipping lines of code alansandbucket 1 4,086 Jun-22-2021, 01:18 AM
Last Post: Larz60+
  [split] Kera Getting errors when following code example Image classification from scratch hobbyist 3 4,546 Apr-13-2021, 01:26 PM
Last Post: amirian
  Running a few lines of code as soon as my timer ends nethatar 3 2,354 Feb-26-2021, 01:02 PM
Last Post: jefsummers
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,165 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Making new lines of code AvioxyYT 1 1,757 Jan-22-2021, 07:02 PM
Last Post: buran

Forum Jump:

User Panel Messages

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