Home > Software design >  How to convert string list into float list
How to convert string list into float list

Time:11-26

I am currently trying to make a program that converts the elements in a string list into a float list. Though a few adjustments have to be made.

  1. The user enters a "colon" between each typed number, which will then divide the elements in the list. (This works atm)

  2. Every value has to be outputted in 1 decimal, which I have been trying to do with:

    print(f'{word:.1f}')
    

    But haven't been able to do it correctly.

Input: 5:2:4

Output: [5.0, 2.0, 4.0]

Would appreciate some recommendations.

user_list = input("Enter values:")
word = user_list.split(":")
print(word)

CodePudding user response:

list(map(float, word.split(':')))

This will convert each of the number to float

CodePudding user response:

You can iterate through each item in array word, convert to float, then round to one decimal using round() and append it to a new array:

user_list = input("Enter values:")
word = user_list.split(":")
newlist = []
for num in word:
    newlist.append(round(float(num), 1))
print(newlist)

Note that this is what you want if you are expecting the user to include longer decimal floats such as 3.432 in their input, and wish them to be outputted as 3.4. If you are assuming the user will only include ints in the input, Sakshi's answer is likely the most compressed solution to do it

CodePudding user response:

Assuming you have validated the inputs, a nice way to do this is through a list comprehension

input = "5:2:4"
user_list = input.split(":")

float_list = [float(x) for x in user_list]
print(float_list)

CodePudding user response:

You can pass a map function into a list function. Your word variable is already being split by ':'. Try list(map(float, word))

CodePudding user response:

This line:

word = user_list.split(":")

Takes a string (user_list) and splits it into parts over occurrences of :. The result is a list of strings. For example, 'alice:bob'.split(":") would become ['alice', 'bob'].

You print all of word, so you're printing a list and that's why you should be seeing ['5', '2', '4'], since that's the representation in text of the list, still in strings.

If you want to print the numbers separated by commas and spaces (for example), with a single digit of precision, you could do:

print(', '.join(f'{float(w):.1f}' for w in word))

This loops over the strings in word, turns them into floating point numbers, then formats them, collects all of them and then .join() puts them all together with ', ' in between.

  • Related