0

List: [['1', '2', '4'],['1', '4', '8'],['03', '8', '6', '1', '62', '7'],['53', '8', '2', '82']]

below code on list :

neighbor1 = [list[i:i + 2] for i in range(0, len(list), 1)]

output:

[[['1', '2', '4'],['1', '4', '8']],[['03', '8', '6', '1', '62', '7'],['53', '8', '2', '82']]]

[[['1', '2', '4'],['1', '4', '8']],[['03', '8', '6', '1', '62', '7'],['53', '8', '2', '82']]]

but i want :

 [[['1','2'],['2','4']],[['1','4'],['4','8']],[['03','8'],['8','6'],['6','1'],['1','62'],['62','7']],[['53','8'],['8','2'],['2','82']]]
joy
  • 1
  • 2
  • You "coded *neighbourhood*" on the top level, but *want* it on the 2nd level? Do you have a question? – greybeard Feb 03 '19 at 22:16
  • Possible duplicate of [How to add data in list below?](https://stackoverflow.com/questions/54508476/how-to-add-data-in-list-below) – whisperquiet Feb 03 '19 at 23:41

2 Answers2

0

You were almost there, you just need to go one level deeper:

[[x[i:i+2] for i in range(len(x)-1)] for x in List]

btw never use keyword list as variable name, or you can run into some really weird things...

Julien
  • 13,986
  • 5
  • 29
  • 53
0

You need to group elements by pairs.

A classic way for that is:

for p, n in zip(your_list[:-1], your_list[1:]):
    pair = p, n

Where p represents each previous element and n represents each next.

With that in hand, you’ll manage to solve your problem.

For instance:

rows = [['1', '2', '4'],
              ['1', '4', '8'],
              ['03', '8', '6', '1', '62', '7'],
              ['53', '8', '2', '82']]

result = [list(zip(row[:-1], row[1:]))
               for row in rows]

print(result)

You get:

[[('1', '2'), ('2', '4')], [('1', '4'), ('4', '8')], [('03', '8'), ('8', '6'), ('6', '1'), ('1', '62'), ('62', '7')], [('53', '8'), ('8', '2'), ('2', '82')]]
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103