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']]
CodePudding user response:
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']]
CodePudding user response:
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.
