简体   繁体   English

我如何从现有列表中创建一个列表(新),其中列表(新)的项目将在 python 中列出

[英]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.

相关问题 我如何从更大的列表中创建一个列表,并且只有 3 个数字 position 到 Python 中的新列表 - how can i create a list from lager list and only 3 number position in to new list in Python 如何使用Python 2中的旧列表创建包含特定项目的新列表? - How do I create a new list with specific items from an old list in Python 2? 如何创建一个新列表,其中每个列表都基于主列表中的项目索引? - How can I make a new list where each list is based on an items index in the main list? 如何在字典和列表之间找到匹配项以从匹配项创建新列表? - How can I find matching items between a dictionary and a list to create a new list from the matches? 如何从前一个x项是外部项的现有项创建嵌套列表? - How can I create a nested list from an existing one where the first x items are the outer items? Python从现有列表创建新列表 - Python Creating a new list from an existing list 如何从现有列表中的值创建新列表 - How to create a new list from values from a existing list 如何从 python 中现有的两个列表中创建新列表? - How to make new list from existing two list in python? 如何将新列表附加到现有列表? - How can I append a new list to an existing list? 如何通过将字符串添加到现有列表而不更改 python 中的现有列表来创建新列表? - How to create a new list by adding a string to existing list without changing the existing list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM