简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM