Shu*_*m R -1 python python-3.x
我有一个列表,其中包含代理和客户之间的聊天对话。
chat = ['agent',
'Hi',
'how may I help you?',
'customer',
'I am facing issue with internet',
'agent',
'Can i know your name and mobile no.?'
'customer',
'john doe',
'111111',..... ]
Run Code Online (Sandbox Code Playgroud)
这是聊天列表的示例。
我希望将列表分为两部分,agent_chatand customer_chat,其中 agent_chat 包含代理所说的所有行,而 customer_chat 包含客户所说的行。
像这样的东西(最终输出)。
agent_chat = ['Hi','how may I help you?','Can i know your name and mobile no.?'...]
customer_chat = ['I am facing issue with internet','john doe','111111',...]
Run Code Online (Sandbox Code Playgroud)
我在解决这个问题时遇到了问题,我尝试使用 list.index() 方法根据索引拆分聊天列表,但是我得到了同一个索引的多个值。
例如,以下代码段:
chat = ['agent',
'Hi',
'how may I help you?',
'customer',
'I am facing issue with internet',
'agent',
'Can i know your name and mobile no.?'
'customer',
'john doe',
'111111',..... ]
Run Code Online (Sandbox Code Playgroud)
Displays [0, 0],因为它只给我第一次出现。
有没有更好的方法来实现所需的输出?
index() 仅返回元素的第一个索引,因此您需要通过遍历列表来累积所有出现的索引。
我建议使用一个简单的 for 循环来解决这个问题:
agent_chat = []
customer_chat = []
chat_type = 'agent'
for chat in chats:
if chat in ['agent', 'customer']:
chat_type = chat
continue
if chat_type == 'agent':
agent_chat.append(chat)
else:
customer_chat.append(chat)
Run Code Online (Sandbox Code Playgroud)
其他方法(如列表理解)需要对列表进行两次迭代。
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |