0

How can I combine every two rows of a string into a paired list of lists?

my code is getting strings from text file:

for fp in oxi_filepath:
    with open(fp, 'r') as dat_file:
        data = dat_file.readlines()

filteredData = list(filter(lambda x: any(True for c in keywords if c in x and 'Value="/' not in x
                                         and 'Value="27' not in x and 'd3333-3333d' not in x), data))

for row in filteredData:
    result = re.search(self.regexpattern, row)
    if result:
        ocr_micr_l.append(result.group(1))

print filtered data...Example

My name is Chris
I like Burgers
My name is John
I like Chicken

output

[['My name is Chris', 'I like Burgers'],['My name is John', 'I like Chicken']]
btava001
  • 131
  • 7
  • What form are the strings in when you start? Is it a text file, a literal string in your code, something else? – Grismar Jan 27 '22 at 04:34
  • @Grismar i edited my post with more info. Its from a text file. – btava001 Jan 27 '22 at 04:35
  • Ah, OK, I see - but by the time you want to pair them up, the lines are already in a list `filteredData` – Grismar Jan 27 '22 at 04:36
  • @Grismar you are correct, i turned it into a string when i did the group(1). I added rest of my code.. I needed to grab that element because it returns a tuple of 3...which is why i did group(1). – btava001 Jan 27 '22 at 04:40

2 Answers2

0

try, splitlines followed by list splicing

text = """My name is Chris
I like Burgers
My name is John
I like Chicken"""

text_split = text.splitlines()

print([[i, j] for i, j in zip(text_split[::2], text_split[1::2])])

[['My name is Chris', 'I like Burgers'], ['My name is John', 'I like Chicken']]
sushanth
  • 8,275
  • 3
  • 17
  • 28
0

Since filteredData is already a list of lines of text, the answer is straightforward:

result = [[a, b] for a, b in zip(filteredData[::2], filteredData[1::2])]

Note that if filteredData has an odd number of items, you may want to add an empty string to the end of it before doing this, as zip() will only pair up items if there's an item for both halves of the pair.

Grismar
  • 27,561
  • 4
  • 31
  • 54