008karan
008karan

Reputation: 411

list comprehension within list of tuple

my problem is something like this:

a=[(0,0,'customer',["Hi, I'm user"]),
 (0,1,'agent',['Hi Welcome']),
 (0,2,'customer',["i would like to know"]),
 (0, 3, 'agent', ['Yes']),
 (0, 3, 'agent', ['Only credit']),
 (0, 4, 'customer', ['oic...']),
 (0, 4, 'customer', ['sub line?']),
 (0, 4, 'customer', ['is it?']),
 (0, 5, 'agent', ['no subline']),
 (0, 6, 'customer', ['oic...']),
 (0, 6, 'customer', ['by']),
 (0, 6, 'customer', ['bye'])]

Need to convert to

a=[(0,0,'customer',["Hi, I'm user"]),
 (0,1,'agent',['Hi Welcome']),
 (0, 2,'customer',["i would like to know"]),
 (0, 3, 'agent', ['Yes','Only credit']),
 (0, 4, 'customer', ['oic...','sub line?','is it?']),
 (0, 5, 'agent', ['no subline']),
 (0, 6, 'customer', ['oic...','by','bye'])]

I want to merge the list of responses based on the speaker (agent/customer). cant find quick logic... any help here?

Upvotes: 0

Views: 83

Answers (1)

Zabir Al Nazi Nabil
Zabir Al Nazi Nabil

Reputation: 11198

You can't change it in_place as it's a tuple, so make another copy and check for pre-existing values to append to the list.

a=[(0,0,'customer',["Hi, I'm user"]),
 (0,1,'agent',['Hi Welcome']),
 (0,2,'customer',["i would like to know"]),
 (0, 3, 'agent', ['Yes']),
 (0, 3, 'agent', ['Only credit']),
 (0, 4, 'customer', ['oic...']),
 (0, 4, 'customer', ['sub line?']),
 (0, 4, 'customer', ['is it?']),
 (0, 5, 'agent', ['no subline']),
 (0, 6, 'customer', ['oic...']),
 (0, 6, 'customer', ['by']),
 (0, 6, 'customer', ['bye'])]

b = []
str2idx = []
idx = 0
for p in a:
  if p[:3] in str2idx:
    b[str2idx.index(p[:3])][3].append(p[3][0])
  else:
    b.append(p)
    str2idx.append(p[:3])
    idx += 1

print(b)

Upvotes: 1

Related Questions