2

I`ve been trying to convert a string numbers list into float and get the max of this list but I keep getting this error:

ValueError: could not convert string to float: '.'

My attempt was to get a list like ls = ['1','2','3','0.5'] and convert using this function

def convert_to_int(ls: list):
    values = [float(a) for a in ls]
    return (len(values), values)

print(max(ls, key=convert_to_int))

Why I'm having this error? Can someone help me?

2
  • 4
    key should be a function which applies to individual elements, not to lists of elements. Also -- why are you calling a function designed to covert to floats convert_to_int? Commented Mar 7, 2022 at 15:05
  • Did you mean max(convert_to_int(ls)[1])? Commented Mar 7, 2022 at 15:12

3 Answers 3

5

I think, what you're looking for is:

max(ls, key=float)

output: '3'

This will get the max value of your string list, using a temporary float conversion within max

Sign up to request clarification or add additional context in comments.

Comments

1

There is a more straight way to do this.

ls = ['1','2','3','0.5']
res = max(map(float, ls))
print(res)

Output:
3.0

Comments

0

Using convert_to_int and ls from the question:

def convert_to_int(ls: list):
    values = [float(a) for a in ls]
    return (len(values), values)

ls = ['1','2','3','0.5']

print(max(*convert_to_int(ls)[1]))

3.0

5 Comments

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
@SumitSChawla how does that not answer the question? Please don't confuse "bad" answers to "not an" answer. If you think this answer is bad - down vote. But we don't delete answers that answer the question
@SumitSChawla I also can't understand your objection.
@MichaelGrazebrook: If you feel the answer is correct. Please add more details to it with sample input and output so that it is clear.
@SumitSChawla It seems pedantic to repeat the question but there you are!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.