[英]How can i create a list (new) from an existing list where items of list(new) will be list in python
I have a list like the following:我有一个如下所示的列表:
original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
And my desired output is:我想要的输出是:
result = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]
Here, the items of 'result' will be each one list of two items from the original_list.这里,'result' 的项目将是来自 original_list 的两个项目的每一个列表。 so if the total no of items in original_list is 8 then it will give like the following:因此,如果 original_list 中的项目总数为 8,那么它将如下所示:
original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
And my desired output is:我想要的输出是:
result = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
I tried to solve that using 2 dimensional matrix but its not working as the elements of the original_list is sometimes even and odd.我试图使用二维矩阵来解决这个问题,但它不起作用,因为 original_list 的元素有时是偶数和奇数。
any suggestion how can i follow?任何建议我该如何遵循?
Is this what you want?这是你想要的吗?
original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
result = []
for i in range(0, len(original_list), 2):
result.append(original_list[i:i+2])
def split_array(original_list,split_size):
result = []
for i in range(0, len(original_list), split_size):
result.append(original_list[i:i+split_size])
return result
original_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print(split_array(original_list,2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.