如果我有一个列表:
{'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;...]
我看过列表库,似乎找不到为此功能
答案 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.map
与int_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] *)
...