Xcecution
Xcecution

Reputation: 1117

How can I compare elements from a list of lists in Python

I have a list of lists of strings and I would like to obtain the largest string on each inner list and store them into another list. For example:

tableData = [['apples','bananas','oranges','cherries'],
            ['Alice','Bob','Carol','David'],
            ['dogs','cats','moose','goose']]

widths = [0] * len(tableData)

I want to store in widths[0], the width of the longest string in tableData[0], in widths[1] the width of the longest string in tableData[1], and so on. How can I compare the length of the words in order to get the greater?

The only way I thought is doing this:

for f in range(len(tableData)):
    for c in range(len(tableData[1])):
        max = len(tableData[f][c])
        if max < len(tableData[f][c+1]):
            max = len(tableData[f][c+1])
    widths[f] = max

Upvotes: 0

Views: 112

Answers (2)

Spherical Cowboy
Spherical Cowboy

Reputation: 566

widths = [len(max(lst, key=len)) for lst in tableData]

For your list of lists called tableData, this gives:

[8, 5, 5]

Explanation:

[max(lst, key=len) for x in tableData] gives you a list containing the longest string of each nested list. Using len(), one then obtains the lengths of these.

The same result can be achieved using:

widths = [len(sorted(lst, key=len)[-1]) for lst in tableData]

Where sorted(lst, key=len) will sort the elements of each list by length, from shortest to longest. Using [-1] one can then obtain the last value of each list, i.e. the longest strings. len()will then compute their lengths.

Upvotes: 2

Charlie G
Charlie G

Reputation: 544

Don't worry about initializing widths. List comprehensions are your friends here.

# creates a list of lists of word lengths
lengths_of_words = [[len(word) for word in x] for x in tableData]

# finds the max length for each list
widths = [max(y) for y in lengths_of_words]

Could also be shortened to

widths = [max([len(word) for word in x]) for x in tableData]

This is the old, incorrect answer if people would like to learn from my mistake:

widths = [len(max(x)) for x in tableData]

Upvotes: -1

Related Questions