按索引拆分列表或列表列表

吉格纳沙·罗亚拉

我想在列表索引i拆分列表:

input_list = `['book flight from Moscow to Paris for less than 200 euro no more than 3 stops', 'Moscow', 'Paris', '200 euro', '3']`

我需要的输出:

output_list = input_list = `[['book flight from Moscow to Paris for less than 200 euro no more than 3 stops'],[ 'Moscow', 'Paris', '200 euro', '3']]`

我试过了:

[list(g) for k, g in groupby(input_list, lambda s: s.partition(',')[0])]

但我得到:

[['book flight from Moscow to Paris for less than 200 euro no more than 3 stops'], ['Moscow'], ['Paris'], ['200 euro'], ['3']]

我怎样才能分成 2 个列表?

jpp

您可以为此使用索引 + 切片。

单人名单

res = [input_list[0], input_list[1:]]

结果:

['book flight from Moscow to Paris for less than 200 euro no more than 3 stops',
 ['Moscow', 'Paris', '200 euro', '3']]

另请参阅了解 Python 的切片符号

名单列表

list_of_list =  [[u'book flight from Moscow to Paris for less than 200 euro no more than 3 stops',
                  u'Moscow', u'Paris', u'200 euro', u'3', u'', u'from_location', u'to_location', u'price',
                  u'stops', u''], [u'get me a flight to Joburg tomorrow', u'Joburg', u'tomorrow', u'',
                  u'to_location', u'departure', u'']]

res2 = [[i[0], i[1:]] for i in list_of_list]

结果:

[['book flight from Moscow to Paris for less than 200 euro no more than 3 stops',
  ['Moscow', 'Paris', '200 euro', '3', '', 'from_location', 'to_location', 'price', 'stops', '']],
 ['get me a flight to Joburg tomorrow',
  ['Joburg', 'tomorrow', '', 'to_location', 'departure', '']]]

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章