You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于索引与条件为列表人名匹配最近关联角色的技术问询

问题:为混乱的姓名-角色列表匹配正确角色

我有一组由姓名和角色组成的列表,但列表的组织逻辑混乱。示例列表如下:

l = ['john', 'owner', 'mark', 'manager', 'alex', 'steve', 'employee', 'manager'] # 最后一个角色无需分配给任何人

需要为每个人名分配其右侧相邻或从左到右最近的角色,期望输出为:

output = [['john', 'owner'], ['mark', 'manager'], ['alex', 'employee'], ['steve', 'employee']]  

我尝试为列表元素添加索引,编写了部分脚本:

parties_role = [(idx, item) for idx,item in enumerate(l)]
    for item in parties_role:
        if "owner" not in str(item[1]) and 'manager' not in str(item[1]) and 'employee' not in str(item[1]):
        name = str(item[1])

现需补充代码,基于索引为当前name变量匹配最近的包含owner、manager、employee关键词的角色。

解决方案

核心思路是先记录所有角色的位置信息,再为每个姓名找到其右侧第一个出现的角色。以下是完整实现代码:

l = ['john', 'owner', 'mark', 'manager', 'alex', 'steve', 'employee', 'manager']

# 收集所有角色的索引与对应值
roles = []
for idx, item in enumerate(l):
    if item in ('owner', 'manager', 'employee'):
        roles.append((idx, item))

output = []
# 遍历列表,为每个姓名匹配最近的右侧角色
for name_idx, name in enumerate(l):
    # 判断当前元素是否为姓名(非角色)
    if name not in ('owner', 'manager', 'employee'):
        # 查找当前姓名之后第一个出现的角色
        for role_idx, role in roles:
            if role_idx > name_idx:
                output.append([name, role])
                break

print(output)

代码逻辑说明

  1. 预存角色信息:先遍历列表,把所有角色的索引和对应值存入roles列表,避免重复判断。
  2. 匹配角色:再次遍历列表,遇到姓名时,从roles中找到第一个索引大于当前姓名索引的角色,这个就是距离最近的右侧角色。
  3. 自动忽略无匹配的角色:最后一个单独的角色因为后面没有姓名,不会被任何姓名匹配到,符合需求。

内容的提问来源于stack exchange,提问作者DouxDoux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 08:03:11