python beginner here. How can I convert
list = [2.4, 4.8532, 5.43253, 55.3838]
to
list = [2, 4, 5, 5]
Thanks.
python beginner here. How can I convert
list = [2.4, 4.8532, 5.43253, 55.3838]
to
list = [2, 4, 5, 5]
Thanks.
you can just use int()
, Since int()
always rounds down toward 0, which is the equivalent of chopping the decimals for floats. Note: do not use list
as a variable name since it's already a built-in function and type.
lst = [2.4, 4.8532, 5.43253]
lst = [int(x) for x in lst]
print(lst)
Output:
[2, 4, 5]
You will have to create a new list, such as with a comprehension. You might want to get the first digit of each element, or possibly get the floor value of each element:
>>> l = [2.4, 4.8532, 5.43253]
>>> l2 = [12.4, 374.8532, -505.43253]
>>> list(map(int, (i[0] for i in map(str, l))))
[2, 4, 5]
>>> list(map(int, l))
[2, 4, 5]
>>> list(map(int, (i[0] for i in map(str, l2))))
>>> [i[0] for i in map(str, l2)]
['1', '3', '-']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-'
>>> list(map(int, l2))
[12, 374, -505]
Note how you will need to be more specific regarding the assumptions about the contents of the list. Can the numbers be greater than 10? Can they be negative? Do you want the first digit of a negative number, or the first character? If it's always 0 < number < 10
, you have nothing to worry about.