Reputation: 55
How to find the longest string in a list?
This list has both strings and list of strings.
a set of strings, but the weirdness comes in that the strings I'm checking are in lists and those lists are mixed in with strings in a larger list.
Example value for 'entries':
extries = [["this is text", "more text"], "another string"]
python code
length = 0
for i in entries:
if(type(i) is list):
for x in i:
x = str(x)
if length << len(max(i, key = len)):
length = len(max(i, key = len))
else:
for i in entries:
i = str(i)
if length << len(i):
length = len(i)
This should make
length = len(max(["this is text","more text","another string"])
but it is making length = 0
.
Upvotes: 2
Views: 1291
Reputation: 26315
For arbitrary deep nested lists, I would first make a list flattening function:
def flatten_nested_list(lst):
for item in lst:
if isinstance(item, list):
yield from flatten_nested_list(item)
else:
yield item
Then you can call max()
with key=len
to get the longest word:
print(max(flatten_nested_list(entries), key=len))
# another string
Upvotes: 1
Reputation: 2551
I'd break the code down in two, first have a function that flattens an arbitrarily deep list:
def flatten(lst, ret):
for x in lst:
if type(x) == list:
flatten(x, ret)
else:
ret.append(x)
Then just use it with your input and an empty list to get a flattened list out, and call max:
temp = []
entries = [["this is text", "more text"], "another string"]
flatten(entries, temp)
max(temp, key=len)
Notice that this would also work with an input like this entries = [[["this is text", "more text"]], ["another string"], "the longest string of them all"]
.
Upvotes: 1
Reputation: 8025
The following code will give you the length of the largest string -- whether or not it is inside a subset.
entries = [["this is text", "more text"], "another string"]
length = 0
for i in entries:
if type(i) is list:
value = len(max(i, key=len))
if length < value:
length = value
else:
value = len(i)
if length < value:
length = value
print(len("this is text"), len("more text"), len("another string"))
print(length)
Outputs:
12 9 14
14
Upvotes: 1