-1

I have below list and would like to split in to sublist with previous alphanumeric value

list = ['P1', 'P2', 'P3', 'P4', 'P5'..........']

Expected output:

output = [['P1', 'P2'],['P2', 'P3'],['P3', 'P4'],['P4', 'P5'],........]

Could anyone please give light on it

vid
  • 11
  • 1

3 Answers3

1

It may not be the most "Pythonic" way of doing it, but here is a solution:

input_list = ['P1', 'P2', 'P3', 'P4', 'P5']
output_list = []

for i in range(1, len(input_list)):
    output_list.append([input_list[i-1], input_list[i]])

print(output_list)
# [['P1', 'P2'], ['P2', 'P3'], ['P3', 'P4'], ['P4', 'P5']]

Ibrahim Berber
  • 842
  • 2
  • 16
0

You can do it as,

>>> n = 2
>>> l = ['P1', 'P2', 'P3', 'P4']
>>> [l[i:i+n] for i in range(0, len(l), n)]
[['P1', 'P2'], ['P3', 'P4']]
>>>
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
0

Using list comprehension:

>>> l1 = ['A', 'B', 'C', 'D', 'E']
>>> [(x,y) for x,y in  zip(l1,l1[1:])]
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E')]
>>>
brokenfoot
  • 11,083
  • 10
  • 59
  • 80