gpt4 book ai didi

python - Itertools 将数组分解为子数组

转载 作者:行者123 更新时间:2023-11-28 21:39:58 26 4
gpt4 key购买 nike

我有一个看起来像这样的字符串数组

['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']

我想把它分解成类似的东西

[['a', 'b', 'c.1'], ['a', 'b', 'c.2'], ['a', 'b', 'c.3'],
['a', 'b', 'd.1'], ['a', 'b', 'd.2'], ['a', 'b', 'd.3'],
['a', 'b', 'd.4']]

我该怎么做?我的想法是在 itertools 中使用 groupby得到类似的东西

['a', 'b', ['c.1', 'c.2', 'c.3'], ['d.1', 'd.2', 'd.3', 'd.4']]

然后可能是这样的

result = []
for elem in nestedList:
if isinstance(elem, list):
temp = []
for elem in nestedList:
if not isinstance(elem, list):
temp.append(elem):
temp.append(elem)
result.append(temp)

为此,我需要访问 groupby 中的下一个元素

(Something like lambda x: '.' not in x and nextelement.split('.')[0] != x)

我该怎么做?

最佳答案

你不需要 itertools。

您可以简单地使用列表推导式来过滤带有或不带 '.' 的字符串,然后在另一个列表推导式中再次组合它们:

data = ['a', 'b', 'c.1', 'c.2', 'c.3', 'c.4', 'd.1', 'd.2', 'd.3']

lone_letters = [x for x in data if '.' not in x]
combined_letters = [x for x in data if '.' in x]

print([lone_letters + [x] for x in combined_letters])
# [['a', 'b', 'c.1'], ['a', 'b', 'c.2'], ['a', 'b', 'c.3'], ['a', 'b', 'c.4'], ['a', 'b', 'd.1'], ['a', 'b', 'd.2'], ['a', 'b', 'd.3']]

关于python - Itertools 将数组分解为子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46194102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com