Python 如何将每 x 个元素拆分一个列表并将这些 x 个元素添加到一个新列表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15890743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you split a list every x elements and add those x amount of elements to an new list?
提问by Tyler
I have a list of multiple integers and strings
我有一个包含多个整数和字符串的列表
['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']
['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']
I'm having difficulty separating the list every 5 elementsand creating a new list with just 5 elements inside.
我很难将每个列表分开5 elements并创建一个内部只有 5 个元素的新列表。
However, I don't want 3 different lists, i just want one that changes every time a new 5 elementsgoes through.
但是,我不想要 3 个不同的列表,我只想要一个每次5 elements通过新列表时都会改变的列表。
回答by Serdalis
You want something like:
你想要这样的东西:
composite_list = [my_list[x:x+5] for x in range(0, len(my_list),5)]
print (composite_list)
Output:
输出:
[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']]
What do you mean by a "new" 5 elements?
你所说的“新”5个元素是什么意思?
If you want to append to this list you can do:
如果您想附加到此列表,您可以执行以下操作:
composite_list.append(['200', '200', '200', '400', 'bluellow'])
回答by Sheng
You could do it in a single sentence like
你可以用一个句子来做,比如
>>> import math
>>> s = ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']
>>> [s[5*i:5*i+5] for i in range(0,math.ceil(len(s)/5))]
Then the output should be :
那么输出应该是:
[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']]
回答by Nick Burns
I feel that you will have to create 1 new list, but if I understand correctly, you want a nested list with 5 elements in each sublist.
我觉得您必须创建 1 个新列表,但如果我理解正确,您需要一个嵌套列表,每个子列表中有 5 个元素。
You could try the following:
您可以尝试以下操作:
l = ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']
new = []
for i in range(0, len(l), 5):
new.append(l[i : i+5])
This will step through your first list, 'l', and group 5 elements together into a sublist in new. Output:
这将逐步遍历您的第一个列表 'l',并将 5 个元素组合到新的子列表中。输出:
[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']]
Hope this helps
希望这可以帮助

