'Longest string from a tuple in a list
i have a list of two string tuples: For example purposes i use this list of tuples but of course the list is generally longer:
[("Hello world","1"), ("Helloworld","2"),("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
The two strings of the tuple are the messages and the sender ID, these messages are of variable length, the only thing that doesn't change is the sender ID. I find myself with a list with multiple messages of different length with the same sender ID, i just want to get a list with the longest message of each sender: e.g. in my example would be:
[("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
I'm a little bit confused as i don't often work with tuples so i really don't know how to procede. I know i should sort the list before doing anything, that's ok, i know to do this but how do i the longest string for each sender after that, knowing that each element of the list is not a string or integer but a tuple?
Thank you very much!
Solution 1:[1]
You could create a dictionary using a comprehension inside the update method:
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'}
You could sort the list beforehand but that would actually be less efficient than the update() approach:
D = dict(map(reversed,sorted(L,key=lambda ms:len(ms[0]))))
{'2': 'HiHelloworld', '1': 'Hi, Hello world', '3': 'How are you'}
Solution 2:[2]
You can map it using a regular dictionary while comparing the current size before insertion:
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'}
I highly suggest leaving the output as a dictionary.
Solution 3:[3]
Once you sort the list, you can create an auxiliary list with all the strings from the same sender ID, and then apply the max function in order to get the longest string out of that auxiliary list.
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
Different approaches can be seen in this post.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Bharel |
| Solution 3 | Atalajaka |
