简体   繁体   English

使用 for 循环和 append 在字符串中的新行之后每次创建一个新列表

[英]Creating a new list each time after a new line in a string using for loop and append

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.我是 Python 的初学者,有一个项目有一长串数字,这些数字由 \n(新行)分隔,所以有很多数字在一起。 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.在此示例中,第一个人持有号码 1000、2000 和 3000,因此他们需要有自己的包含这些号码的列表,第二个人需要有自己的包含他们的号码的列表,依此类推。

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.我需要每个人都有自己的数字列表,但是当我使用 string.split() function 时,它将所有数字放入一个包含空格的大列表中。 How can I use the for loop and.append() to create a new lists each time a \n is met by creating a method?每次通过创建方法满足 \n 时,如何使用 for 循环和 .append() 创建新列表?

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].我需要它是 [1000,2000,3000]、[4000,5000,6000]、[7000,8000,9000] 和 [10000]。 Help and clarification would be appreciated!帮助和澄清将不胜感激!

Assuming s the input string, you can split first on double newlines, then on newlines:假设s输入字符串,您可以先在双换行符上拆分,然后在换行符上拆分:

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,如果有悬空空格/换行符, strip只是一种安全,

Output: Output:

[[1000, 2000, 3000],
 [4000, 5000, 6000],
 [7000, 8000, 9000],
 [10000]
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM