2021年3月19日星期五

How to chain, and then "unchain" a nested list?

I have a nested list that I need to chain, then run metrics, then "unchain" back into its original nested format. Here is example data to illustrate:

from itertools import chain    nested_list = [['x', 'xx', 'xxx'], ['yy', 'yyy', 'y', 'yyyy'], ['zz', 'z']]  chained_list = list(chain(*nested_list))  print("chained_list: \n", chained_list)  metrics_list = [str(chained_list[x]) +'_score' \      for x in range(len(chained_list))]  print("metrics_list: \n", metrics_list)   zipped_scores = list(zip(chained_list, metrics_list))  print("zipped_scores: \n", zipped_scores)    unchain_function = '????'    chained_list:    ['x', 'xx', 'xxx', 'yy', 'yyy', 'y', 'yyyy', 'zz', 'z']  metrics_list:    ['x_score', 'xx_score', 'xxx_score', 'yy_score', 'yyy_score', 'y_score', 'yyyy_score', 'zz_score', 'z_score']  zipped_scores:    [('x', 'x_score'), ('xx', 'xx_score'), ('xxx', 'xxx_score'), ('yy', 'yy_score'), ('yyy', 'yyy_score'), ('y', 'y_score'), ('yyyy', 'yyyy_score'), ('zz', 'zz_score'), ('z', 'z_score')]  

Is there a python function or pythonic way to write an "unchain_function" to get this DESIRED OUTPUT?

[      [          ('x', 'x_score'),           ('xx', 'xx_score'),           ('xxx', 'xxx_score')      ],      [          ('yy', 'yy_score'),           ('yyy', 'yyy_score'),           ('y', 'y_score'),          ('yyyy', 'yyyy_score')      ],      [          ('zz', 'zz_score'),           ('z', 'z_score')      ]  ]  

(background: this is for running metrics on lists having lengths greater than 100,000)

https://stackoverflow.com/questions/66666810/how-to-chain-and-then-unchain-a-nested-list March 17, 2021 at 12:01PM

没有评论:

发表评论