簡體   English   中英

元組列表中的列表理解

[英]list comprehension within list of tuple

我的問題是這樣的:

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

我想根據發言人(代理/客戶)合並響應列表。 找不到快速邏輯...這里有什么幫助嗎?

您不能在 in_place 更改它,因為它是一個元組,因此制作另一個副本並檢查 append 到列表中的預先存在的值。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM