lst = ["aa", "lot", "bb", "obj", "obj", "obj", "cc", "lot", "obj", "gg", "lot", "obj", "obj"]
lot = [i for i, x in enumerate(lst) if x == "lot"]
obj = [lst[a:b].count("obj") for a, b in zip(lot, lot[1:] + [len(lst)])]
print(obj) # [3, 1, 2]
或者首先从列表中删除“垃圾”,然后您不需要子列表和count之后:
lst = [x for x in lst if x in ("lot", "obj")]
lot = [i for i, x in enumerate(lst) if x == "lot"]
obj = [b - a - 1 for a, b in zip(lot, lot[1:] + [len(lst)])]
from collections import OrderedDict
d = OrderedDict()
for n, i in enumerate(l):
if i == "lot":
d[n] = [i]
elif i == "obj":
d[max(d)].append(i)
list(d.values())
def group_lots(inp):
count = 0
seen_lot = False
for item in inp:
if item == "obj":
count += 1
if item == "lot":
if seen_lot:
yield count
count = 0
seen_lot = True
if count:
yield count
print(list(group_lots(inp))) # [3, 1, 2]
或无法阅读的神秘魔法itertools.groupby表达式:
import itertools
obj_counts = [
len(list(group_contents))
for is_lot, group_contents in itertools.groupby(
(item for item in inp if item in ("lot", "obj")),
lambda i: i == "lot",
)
if not is_lot
]
print(obj_counts) # [3, 1, 2]
您可以使用
enumerate
获取lot
位置,然后计算子列表中的obj
:或者首先从列表中删除“垃圾”,然后您不需要子列表和
count
之后:(两者都不会计算第一个
lot
之前的任何obj
,而是在最后一个之后。)使用
OrderedDict
的一种方法:输出:
根据您的意见:
两种方法:
相关问题 更多 >
编程相关推荐