提问人:Robert Tuttle 提问时间:8/3/2023 最后编辑:MarkRobert Tuttle 更新时间:8/3/2023 访问量:46
根据条件将列表分解为嵌套列表
Break list into nested lists based on criteria
问:
我有一个与此类似的列表,但要长得多:
master_list=[[foo, fum, A, fee, 5, see, V, G],[B, foo, flo, 6, lee, D, 8, 9]]
我希望将这个嵌套列表中的列表分解为它们自己的嵌套列表。如果列表中的元素位于单独的列表中,则它将包含在嵌套列表中。否则,它将被排除在外。所以:
elements=[foo, fum, 5, flo, lee, D, V]
我最终会得到以下结果:
final_list=[[[foo, fum], A, fee, [5], see, [V], G],[B, [foo, flo], 6, [lee, D], 8, 9]]
我试过了这个,但效果不佳:
final_list=[]
for master in master_test:
result = []
temp_list = []
for i in master:
if i in cols:
temp_list.append(i)
result.append(temp_list)
else:
temp_list = []
result.append(i)
result.append(temp_list)
final_list.append(result)
答:
1赞
Tzane
8/3/2023
#1
这应该可以做到
master_test = [
["foo", "fum", "A", "fee", 5, "see", "V", "G"],
["B", "foo", "flo", 6, "lee", "D", 8, 9]
]
cols = ["foo", "fum", 5, "flo", "lee", "D", "V"]
final_list = []
for master in master_test:
result = []
temp_list = []
for i in master:
if i in cols:
temp_list.append(i)
else:
if temp_list:
result.append(temp_list)
temp_list = []
result.append(i)
if temp_list:
result.append(temp_list)
final_list.append(result)
print(final_list)
必须进行 2 次更改:
从 else 语句移动到空列表并添加一个检查器
result.append(temp_list)
if i in cols
在循环后添加一个空列表检查器
result.append(temp_list)
for i in master
评论
1赞
AKX
8/3/2023
if len(temp_list)
简化为 .if temp_list
2赞
AKX
8/3/2023
#2
使用标准库函数和生成器:itertools.groupby
from itertools import groupby
def group_by_elements(l, elements):
for flag, group in groupby(l, lambda x: x in elements):
if flag:
yield list(group)
else:
yield from group
master_test = [
["foo", "fum", "A", "fee", 5, "see", "V", "G"],
["B", "foo", "flo", 6, "lee", "D", 8, 9],
]
elements = ["foo", "fum", 5, "flo", "lee", "D", "V"]
print([list(group_by_elements(m, elements)) for m in master_test])
这输出
[
[['foo', 'fum'], 'A', 'fee', [5], 'see', ['V'], 'G'],
['B', ['foo', 'flo'], 6, ['lee', 'D'], 8, 9],
]
0赞
Alain T.
8/3/2023
#3
groupby
是最好的工具。您可以在基于元素列表中是否存在主条目构建子列表的推导式中使用它:
from itertools import groupby
master = [
["foo", "fum", "A", "fee", 5, "see", "V", "G"],
["B", "foo", "flo", 6, "lee", "D", 8, 9],
]
elems = ["foo", "fum", 5, "flo", "lee", "D", "V"]
final = [ [r for nest,(*g,) in groupby(m,key=elems.__contains__)
for r in [g,[g]][nest] ]
for m in master ]
print(final)
[
[['foo', 'fum'], 'A', 'fee', [5], 'see', ['V'], 'G'],
['B', ['foo', 'flo'], 6, ['lee', 'D'], 8, 9]
]
评论