0

I want to split list at index i of list:

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

My required output:

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

I tried:

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

But I get:

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

How can I split into only 2 lists?

jpp
  • 159,742
  • 34
  • 281
  • 339
Jignasha Royala
  • 1,032
  • 10
  • 27

1 Answers1

1

You can use indexing + slicing for this.

Single list

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

Result:

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

See also Understanding Python's slice notation.

List of lists

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]

Result:

[['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', '']]]
jpp
  • 159,742
  • 34
  • 281
  • 339