{
"key1" : <list of strings>,
"key2" : <list of integeres> }
我想更改&#39; key2&#39;的类型列表到int。 我已经尝试过循环并使用
v = int(v)
我也尝试将int映射到整个列表。
map(int,list)
我能以其他方式完成这项任务吗?
当前代码:
integer_columns = ["col1","col2","col3","col4"]
for col in integer_columns:
col_list = config_data[col]
col_list = list(map(int, col_list))
答案 0 :(得分:2)
map
有什么问题?
d['key2'] = map(int, d['key2'])
或d['key2'] = list(map(int, d['key2']))
:
d = {'key2': ['1', '2', '3']}
print(d)
d['key2'] = list(map(int, d['key2']))
print(d)
输出
{'key2': ['1', '2', '3']}
{'key2': [1, 2, 3]}
OP更新问题后编辑
for col in integer_columns:
col_list = config_data[col] # col_list references to config_data[col]
col_list = list(map(int, col_list)) # now col_list references to an entire
# new list of ints, that has nothing to do
# with config_data[col]
col_list
正在修改,但此更改未反映回config_data[col]
。相反,做一些类似于我在上面的原始答案中所展示的内容:
for col in integer_columns:
config_data[col] = list(map(int, config_data[col]))
答案 1 :(得分:0)
修复了错误。
假设您有一个dict,每个键映射到numpy.int64列表。
<强>设置强>
d = {'key2':[np.int64(v) for v in xrange(10)]}
<强>试验强>
%timeit -n 1000 d['key2'] = map(int, d['key2'])
1000 loops, best of 3: 1.5 µs per loop
%timeit -n 1000 d['key2'] = [int(v) for v in d['key2']]
1000 loops, best of 3: 2.0 µs per loop
%timeit -n 1000 d['key2'] = [np.asscalar(v) for v in np.array(d['key2'])]
1000 loops, best of 3: 11.6 µs per loop
使用您当前的代码更新:
integer_columns = ["col1","col2","col3","col4"] # assuming you have a list of list here
for col in integer_columns:
x = np.array(col)
config_data[col] = [np.asscalar(v) for v in x]
# >>> type(integer_columns[0][1])
# >>> int
numpy.asscalar是numpy中的一个函数,用于将numpy类型转换为本机python类型。这里很好answer解释它。
因此,确实有其他方法可以做到这一点,这取决于您对特定解决方案的特定情况。