0

I'm a beginner in Python and have a project that has a long list of numbers that are separated by \n (new line) so there are chuncks of numbers together. The long list of numbers is presented as a string and I need to first put them in a list then convert them to integers.

Here is the test list of numbers:

1000
2000
3000

4000
5000
6000

7000
8000
9000

10000

Each group represents one person, so each person needs to have their own list. In this example, person one is holding numbers 1000, 2000, and 3000 so they need to have their own list with these numbers and the second person needs to have their own list with their numbers and so on.

I need each person to have their own list with their numbers, but when I use the string.split() function, it puts all of the numbers into one large list including the spaces. How can I use the for loop and .append() to create a new lists each time a \n is met by creating a method?

This is my code so far:

def converting(lists):
  new_list = []
  for i in lists:
    lists = new_list.append(i)

  print(new_list)

How would I create individual lists each time a new line is seen? I was expecting it to create a new list each time, but it resulted in this:

['\n', '1', '0', '0', '0', '\n', '2', '0', '0', '0', '\n', '3', '0', '0', '0', '\n', '\n', '4', '0', '0', '0', '\n', '\n', '5', '0', '0', '0', '\n', '6', '0', '0', '0', '\n', '\n', '7', '0', '0', '0', '\n', '8', '0', '0', '0', '\n', '9', '0', '0', '0', '\n', '\n', '1', '0', '0', '0', '0']

It instead took every single character and outputted it into one large string.

I need it to be [1000,2000,3000], [4000,5000,6000], [7000,8000,9000] and [10000]. Help and clarification would be appreciated!

PM 77-1
  • 12,933
  • 21
  • 68
  • 111

1 Answers1

2

Assuming s the input string, you can split first on double newlines, then on newlines:

out = [list(map(int, s2.strip().split('\n')))
       for s2 in s.strip().split('\n\n')]

NB. the strip are only a safety in case there are dangling spaces/newlines,

Output:

[[1000, 2000, 3000],
 [4000, 5000, 6000],
 [7000, 8000, 9000],
 [10000]
]
mozway
  • 194,879
  • 13
  • 39
  • 75