【问题标题】:For loop - Create list in list for max three itemsFor 循环 - 在列表中创建最多三个项目的列表
【发布时间】:2020-05-12 22:30:17
【问题描述】:

问题:

我想制作一个子列表字符串计数为 3 的列表。我用矩阵技术尝试过它,但到目前为止它不起作用。

我无法计数,创建列表,第一个元素,第二个元素,第三个元素,创建新列表,插入第四个元素,第五个元素,第六个元素,创建新列表...

如果代码也可以处理不能被 3 整除的项目列表长度,那就太好了。就像我的源列表中的 8 个字符串一样。

样本数据:

my_list = ['Item11', 'Item12', 'Item13', 'Item24', 'Item25', 'Item26', 'Item37', 'Item38', 'Item39']

我的尝试:

sublist = []
for mainlist in range(3):
    # Append an empty sublist inside the list
    mainlist.append([])
    for item in my_list:
        for sublist in mainlist:
            sublist.append(item)

print(sublist)

预期结果:

my_list = [['Item11', 'Item12', 'Item13'], ['Item24', 'Item25', 'Item26'], ['Item37', 'Item38', 'Item39']]

【问题讨论】:

  • 这似乎需要更多解释:输出列表中的字符串与输入中的字符串不匹配。但是,您的代码中没有任何内容可以影响该更改。
  • @Prune 很抱歉我更新了结果。我打错了,现在应该匹配了。
  • 这似乎是重复的——但你必须知道这被称为“分块”列表。搜索“Python 块列表”。
  • 我目前正在查找它。到目前为止,从未听说过“分块”这个词。我会及时通知你。
  • 不开玩笑......这不是一个正式的 Python 术语,只是数据处理程序所称的过程。

标签: python list for-loop nested-lists


【解决方案1】:

它被称为“yield chunks”,在被告知术语是什么后我发现了一个线程。

List to Stackoverflow solutions to chunck a list

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]


print(list(chunks(my_list, 3)))

使用 itertools 的第二种解决方案:

#from itertools import izip_longest as zip_longest # for Python 2.x
from itertools import zip_longest # for Python 3.x
#from six.moves import zip_longest # for both (uses the six compat library)

def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

print(grouper(3, my_list)))

【讨论】:

  • 在链接到您所做的页面后,如果您决定引用其中的一些代码,为什么不使用基于列表理解的最简单的代码。我建议您将其作为您引用的最佳解决方案(可能是唯一的解决方案)。
【解决方案2】:

我认为这就是您要查找的内容(如果 my_list 中的项目数不能被 3 整除,也可以使用):

my_list = ['Item11', 'Item12', 'Item13', 'Item24', 'Item25', 'Item26', 'Item37', 'Item38', 'Item39']

mainlist = []
if len(my_list) < 3:
    mainlist.append(my_list)
else:
    # The magic is here
    first_items = my_list[::3]
    second_items = my_list[1::3]
    third_items = my_list[2::3]

    for i in range(len(third_items)):
        temp_list = [first_items[i], second_items[i], third_items[i]]
        mainlist.append(temp_list)

    # This if is for when the number of items are not divisible by 3
    if len(second_items) > len(third_items):
        if len(first_items) > len(second_items):
            mainlist.append([first_items[-1]])
        else:
            mainlist.append([first_items[-1], second_items[-1]])

print(mainlist)

【讨论】:

  • 谢谢,这是一个有趣的解决方案。我正在仔细研究你的结构!
  • 这是一个有趣的解决方案,但相对于单行来说过于复杂:[lst[i:i + n] for i in range(0, len(lst), n)](@BenjaminK 的答案链接到的部分页面)
  • @DanielLavedoniodeLima 您能否在您的解决方案中解释一下 [::3]。谢谢
  • @BenjaminK 当然。所以这在 Python 中被称为“切片”。 StackOverflow 已经有一个很好的解释,official Python tutorial 有一个(不太好)。
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 2020-11-14
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
相关资源
最近更新 更多