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

时间:2018-03-19 11:29:43

标签: python python-3.x list

我想在列表的索引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个列表?

1 个答案:

答案 0 :(得分:1)

您可以使用索引+切片。

单一列表

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']]

另见Understanding Python's slice notation

列表清单

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', '']]]