Answer the question
In order to leave comments, you need to log in
Mapping two lists and outputting blocks based on the number of values in one of them?
Hello.
I think that the issue is solved more easily than I thought of it, but my head is already fixated and does not find another way out. Hope you suggest it.
There is an array of data presented in plain text. This array represents values for several entities at once. These entities themselves are placed in a separate list. The values for each entity come in blocks separated by a blank line. An example is below in the code. The number of values per entity can vary.
dataset_names = ["moscow", "new-york"]
text = """2008 11 186
2009 11 281
2011 11 776
2012 11 856
2011 11 776
2012 11 856"""
def chunks(l, n=2):
"""Разбивает список (l) на части размером n"""
for i in range(0, len(l), n):
yield l[i:i + n]
prepare_text = text.replace(' ','').replace('\n','\t').split('\t\t')
data = [list(chunks(item.split('\t'))) for item in prepare_text]
Answer the question
In order to leave comments, you need to log in
import re
dataset_names = ["moscow", "new-york"]
text = """2008 11 186
2009 11 281
2011 11 776
2012 11 856
2011 11 776
2012 11 856"""
prepare_text = re.split('\t+|\n+', text)
out = {k: [{'value_{}'.format(i+1): prepare_text[t+i] for i in range(2)} for t in range(0,len(prepare_text), 2)] for k in dataset_names}
print(out)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question