作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果我有一个列表
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/
我是一名优秀的程序员,十分优秀!