I have a list of tuples with each tuple containing two values. The first value is a list of strings, the second value is a string:
list_of_tuples = [(['this', 'askjsdaddsa', 'match1'], 'done'), (['sajs', 'skasassas', 'asdasdasdasd', 'qwerty'], 'doneagain')]
How can I reduce the first value within the tuple to only the strings that contain six letters? Ideally I would have
final_list_of_tuples = [('match1' , 'done'), ('qwerty', 'doneagain')]
So far I have the following:
for a, b in dict_refine:
a.remove(i for i in a if len(i) != 6)
I feel as if there is something very elementary that I am blowing right past. Is there a way to do this in one line? Would it be easier to output into a dictionary?
As with most tasks involving changing a list in Python, the tool for the job here is probably the list comprehension, in this instance, two of them:
>>> [([word for word in words if len(word) == 6], key) for (words, key) in list_of_tuples]
[(['match1'], 'done'), (['qwerty'], 'doneagain')]
The inner comprehension [word for word in words if len(word) == 6] is hopefully clear - this filters the list down to words of length six. The outer one just applies that inner one to the first element of each tuple and reconstructs the tuple.
If you are working directly with the values, of course, there is no need to construct a new list, you can just iterate normally:
for (words, key) in list_of_tuples:
six_letter_words = [word for word in words if len(word) == 6]
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With