Divide list into two parts based on condition python

I have a list which contains a chat conversation between agent and customer.

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',..... ]

This is a sample of chat list.

I am looking to divide the list into two parts, agent_chat and customer_chat, where agent_chat contains all the lines that agent said, and customer_chat containing the lines said by customer.

Something like this(final output).

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',...]

I’m facing issues while solving this, i tried using list.index() method to split the chat list based on indexes, but I’m getting multiple values for the same index.

For example, the following snippet:

[chat.index(l) for l in chat if l=='agent']

Displays [0, 0], since its only giving me first occurrence.

Is there a better way to achieve the desired output?

Answer

This would be my solution to your problem.

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']

agent_list = []
customer_list = []

agent = False
customer = False
for message in chat:
    if message == 'agent':
        agent = True
        customer = False
    elif message == 'customer':
        agent = False
        customer = True
    elif agent:
        agent_list.append(message)
    elif customer:
        customer_list.append(message)
    else:
        pass

Leave a Reply

Your email address will not be published. Required fields are marked *