转换/转换浮点列表为int列表

时间:2019-04-15 22:55:20

标签: ocaml

如果我有一个列表:

{'Debug': <class '__main__.Debug'>,
 '__builtins__': <module 'builtins' (built-in)>,
 '__cached__': None,
 '__doc__': None,
 '__file__': '/home/user1/main-projects/overflow/file.py',
 '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f7bbb44f7f0>,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 'i_will_be_in_the_locals': 42,
 'inspect': <module 'inspect' from '/usr/lib/python3.5/inspect.py'>}

是否可以将其转换或转换为整数列表:

[1.0;2.0;3.0;...]

我看过列表库,似乎找不到为此功能

2 个答案:

答案 0 :(得分:3)

// given a type T, defines a static member function called f that routes to the correct form of printdata.
// default implementation goes to int version.
template<typename T> struct _get_version { static void f(T val) { printdata(static_cast<uint32_t>(val)); } };

// specialize this for all the floating point types (float, double, and long double).
template<> struct _get_version<float> { static void f(float val) { printdata(static_cast<float>(val)); } };
template<> struct _get_version<double> { static void f(double val) { printdata(static_cast<float>(val)); } };
template<> struct _get_version<long double> { static void f(long double val) { printdata(static_cast<float>(val)); } };

template<typename Data>
void myTemplate(Data d)
{
    // get the version Data should use, then use its internal f function
    _get_version<Data>::f(d);
}

采用函数utop # List.map;; - : ('a -> 'b) -> 'a list -> 'b list = <fun> ,该函数将类型f : 'a -> 'b的值带入类型'a的值,并将函数从'b的列表返回到'a列表:

'b

在这种情况下,utop # List.map int_of_float;; - : float list -> int list = <fun> 是我们的int_of_float : int -> float,因此我们获得了从f列表到float列表的功能。

int

答案 1 :(得分:1)

您可以尝试将List.mapint_of_float结合使用,将浮点数转换为整数。

示例:

let float_list = [1.0; 2.0; 3.0] in
let int_list = List.map (fun x -> int_of_float x) float_list in
(* int_list is [1; 2; 3] *)
...
相关问题