Reputation: 403
I am trying to find the longest string in a nested list using the below code
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
cnt = [""]*3
for tab in range(len(table_data)):
for liel in table_data[tab]:
if len(liel) > len(cnt[tab]):
cnt[tab]=liel
print(cnt)
# ['cherries', 'Alice', 'moose']
The above code is returning the longest string in each list, but I think its long code, is there any other way to do this?
Expecting any ways to do this using List comprehension or function
Regards
Upvotes: 2
Views: 81
Reputation: 7846
Another way to achieve your result would be to use the map
function, althouth this does not utilize list comprehension:
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
output = list(map(lambda data: max(data, key=len),table_data))
print(output)
Output:
['cherries', 'Alice', 'moose']
Upvotes: 1
Reputation: 362497
Expecting any ways to do this using List comprehension
Yes, list comprehension is a good choice.
>>> [max(row, key=len) for row in table_data]
['cherries', 'Alice', 'moose']
Upvotes: 8