-1

lets say i have text file

1234
5678
9012
3456
7890
1245
3678
4367
3454
4536
8768
1678

i want to extract all these into list and then convert that list into a list of lists of length say 2 so it should become

[[1234,5678],[9012,3456],[7890,1245]..........]

so far i am doing this:

with open(infile) as f:
    all_stores =[]
    batch=[next(f).rstrip() for x in range(2)]
    all_stores.append(batch)

I also tried list comprehensions . but i am doing it wrong

# mylist=[[all[stores] for i in range(10)]for el in all_stores]

Would appreciate some help.I am using Python and a windows 10. sorry for being a noob.

nsingh
  • 61
  • 1
  • 5
  • https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – nsingh Aug 06 '21 at 21:39

2 Answers2

1

You can achieve it in this way, using zip function :

Pairing the elements

pairs = zip(my_list[::2], my_list[1::2])

BlackMath
  • 1,708
  • 1
  • 11
  • 14
1

Could you try this?

nw_lst = [[lst[x],lst[x+1]] for x in range(0,len(lst),2)]

Here, lst is the list of the numbers at first.


If there is a possibility of the length of the list is odd:

nw_lst = [[lst[x],lst[x+1]] for x in range(0,len(lst)-1,2)]
if len(lst)%2==0:
    nw_lst.append([lst[len(lst)-2],lst[len(lst)-1]])
else:
    nw_lst.append([lst[len(lst)-1]])
nadirhan
  • 160
  • 2
  • 12