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)
CodePudding user response:
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]]