gpt4 book ai didi

python - 如何将列表拆分为元组

转载 作者:太空狗 更新时间:2023-10-30 01:56:25 25 4
gpt4 key购买 nike

如果我有一个列表

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']  

我想拆分成没有“k”的新列表,并将其变成一个元组。所以我得到了

(['a'],['b', 'c'], ['d', 'e', 'g'])

我正在考虑首先使用 for 循环将它们分成不同的列表。

new_lst = []
for element in lst:
if element != 'k':
new_ist.append(element)

这确实删除了所有“k”,但它们都在一起。我不知道如何将它们分成不同的列表。要将列表变成元组,我需要在列表中创建一个列表

a = [['a'],['b', 'c'], ['d', 'e', 'g']]
tuple(a) == (['a'], ['b', 'c'], ['d', 'e', 'g'])
True

所以问题是如何将列表拆分为带有子列表的列表。

最佳答案

你很接近。您可以附加到另一个名为 sublist 的列表,如果您找到 k,则将 sublist 附加到 new_list:

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']

new_lst = []
sublist = []
for element in lst:
if element != 'k':
sublist.append(element)
else:
new_lst.append(sublist)
sublist = []

if sublist: # add the last sublist
new_lst.append(sublist)

result = tuple(new_lst)
print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

如果您喜欢冒险,也可以使用 groupby .这个想法是将元素分组为“k”或“非 k”并在该属性上使用 groupby:

from itertools import groupby

lst = ['a', 'k', 'b', 'c', 'k', 'd', 'e', 'g']
result = tuple(list(gp) for is_k, gp in groupby(lst, "k".__eq__) if not is_k)

print(result)
# (['a'], ['b', 'c'], ['d', 'e', 'g'])

感谢@YakymPirozhenko 提供更简单的生成器表达式

关于python - 如何将列表拆分为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53550613/

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