如何将每 x 个元素拆分一个列表并将这些 x 个元素添加到一个新列表中? [英] How can you split a list every x elements and add those x amount of elements to an new list?

查看:14
本文介绍了如何将每 x 个元素拆分一个列表并将这些 x 个元素添加到一个新列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个整数和字符串的列表

I have a list of multiple integers and strings

['-200', '0', '200', '400', 'green', '0', '0', '200', '400', '黄色', '200', '0', '200', '400', '红色']

我很难将列表每 5 个元素分开并创建一个只有 5 个元素的新列表.

I'm having difficulty separating the list every 5 elements and creating a new list with just 5 elements inside.

但是,我不想要 3 个不同的列表,我只想要一个每次通过新的 5 个元素 时都会改变的列表.

However, I don't want 3 different lists, i just want one that changes every time a new 5 elements goes through.

推荐答案

你想要的是:

composite_list = [my_list[x:x+5] for x in range(0, len(my_list),5)]

print (composite_list)

输出:

[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']]

新"的 5 个元素是什么意思?

What do you mean by a "new" 5 elements?

如果你想附加到这个列表,你可以这样做:

If you want to append to this list you can do:

composite_list.append(['200', '200', '200', '400', 'bluellow'])

这篇关于如何将每 x 个元素拆分一个列表并将这些 x 个元素添加到一个新列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆