Issue
Hey :) How can I compare lists so that all elements of the lists match except for one element the color? If all other elements match, the lists should be concatenated into one.
fruitlist = [['Apple', 'red', 10], ['Apple', 'green', 10], ['Apple', 'pink', 10], ['Apple', 'yellow', 20], ['Banana', 'yellow', 10]]
output:
fruitlist = [['Apple', 'red, green, pink', 10], ['Apple', 'yellow', 20],['Banana', 'yellow', 10]]
Is there also a solution here that applies to much longer lists? (excluding one or more elements)
Solution
Use an intermediate dictionary then construct your output list as follows:
from collections import defaultdict
mdict = defaultdict(list)
fruitlist = [['Apple', 'red', 10], ['Apple', 'green', 10], ['Apple', 'pink', 10], ['Apple', 'yellow', 20], ['Banana', 'yellow', 10]]
for fruit, colour, n in fruitlist:
mdict[fruit, n].append(colour)
print([[fruit, ', '.join(v), n] for (fruit, n), v in mdict.items()])
Output:
[['Apple', 'red, green, pink', 10], ['Apple', 'yellow', 20], ['Banana', 'yellow', 10]]
Answered By - Arthur King
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.