[英]Longest string from a tuple in a list
我有兩個字符串元組的列表:例如,我使用這個元組列表,但當然列表通常更長:
[("Hello world","1"), ("Helloworld","2"),("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
元組的兩個字符串是消息和發送者 ID,這些消息是可變長度的,唯一不變的是發送者 ID。 我發現自己有一個列表,其中包含多個不同長度且具有相同發件人 ID 的消息,我只想獲得一個包含每個發件人最長消息的列表:例如,在我的示例中是:
[("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
我有點困惑,因為我不經常使用元組,所以我真的不知道如何進行。 我知道我應該在做任何事情之前對列表進行排序,沒關系,我知道這樣做,但是在那之后我如何為每個發件人設置最長的字符串,知道列表的每個元素不是字符串或 integer 而是一個元組?
非常感謝!
您可以使用字典 ( defaultdict
) 來跟蹤每個 ID 的最長消息:
from collections import defaultdict
# input
l = [("Hello world","1"), ("Helloworld","2"),("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
d = defaultdict(lambda:('', float('-inf')))
for msg, ID in l:
if len(msg) > len(d[ID][0]):
d[ID] = (msg, ID)
out = list(d.values())
output:
[('Hi, Hello world', '1'), ('HiHelloworld', '2'), ('How are you', '3')]
您可以使用常規字典 map 它,同時在插入前比較當前大小:
messages = [("Hello world","1"), ("Helloworld","2"),("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
def get_longest_messages(messages):
output = {}
for message, sender in messages:
if len(message) > len(output.get(sender, "")):
output[sender] = message
return output
print(get_longest_messages(messages))
Output:
{'1': 'Hi, Hello world', '2': 'HiHelloworld', '3': 'How are you'}
我強烈建議將 output 作為字典。
您可以使用 update 方法中的理解來創建字典:
L = [("Hello world","1"), ("Helloworld","2"),("Hi, Hello world","1"),
("How are you","3"),("HiHelloworld","2")]
D = dict()
D.update((s,m) for m,s in L if len(m)>=len(D.get(s,'')))
{'1': 'Hi, Hello world', '2': 'HiHelloworld', '3': 'How are you'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.