转换字典中列表值的元素 Python
convert Element of list value in Dictionary Python
我有这样的数据
[{'point1': ['20.900', '15.300', '20.400'],
'point2': ['0.600', '34.700', '8.100'],
'point3': ['12.100', '15.800', '2.300'],
'point4': ['15.000', '5.800', '16.900']}]
如何将数字转换为整数?
您可以使用循环:
for d in lst:
for v in d.values():
for i, num in enumerate(v):
v[i] = int(float(num))
print(lst)
输出:
[{'point1': [20, 15, 20],
'point2': [0, 34, 8],
'point3': [12, 15, 2],
'point4': [15, 5, 16]}]
在一行中试试这个:
l = [{'point1': ['20.900', '15.300', '20.400'], 'point2': ['0.600', '34.700', '8.100'], 'point3': ['12.100', '15.800', '2.300'], 'point4': ['15.000', '5.800', '16.900']}]
result = [{k: [int(float(i)) for i in v] for k, v in l[0].items()}]
结果将是:
[{'point1': [20, 15, 20],
'point2': [0, 34, 8],
'point3': [12, 15, 2],
'point4': [15, 5, 16]}]
array=[{'point1': ['20.900', '15.300', '20.400'], 'point2': ['0.600', '34.700', '8.100'], 'point3': ['12.100', '15.800', '2.300'], 'point4': ['15.000', '5.800', '16.900']}]
new_array=array[0]
for i in new_array.values():
k=0
for j in i:
i[k]=int(float(j))
k=k+1
print(new_array)
a similar question 已经问过了!
你也可以这样做:
arr = [{
'point1': ['20.900', '15.300', '20.400'],
'point2': ['0.600', '34.700', '8.100'],
'point3': ['12.100', '15.800', '2.300'],
'point4': ['15.000', '5.800', '16.900'],
}]
[{k : list(map(float, v)) for k, v in point.items() } for point in arr]
我有这样的数据
[{'point1': ['20.900', '15.300', '20.400'],
'point2': ['0.600', '34.700', '8.100'],
'point3': ['12.100', '15.800', '2.300'],
'point4': ['15.000', '5.800', '16.900']}]
如何将数字转换为整数?
您可以使用循环:
for d in lst:
for v in d.values():
for i, num in enumerate(v):
v[i] = int(float(num))
print(lst)
输出:
[{'point1': [20, 15, 20],
'point2': [0, 34, 8],
'point3': [12, 15, 2],
'point4': [15, 5, 16]}]
在一行中试试这个:
l = [{'point1': ['20.900', '15.300', '20.400'], 'point2': ['0.600', '34.700', '8.100'], 'point3': ['12.100', '15.800', '2.300'], 'point4': ['15.000', '5.800', '16.900']}]
result = [{k: [int(float(i)) for i in v] for k, v in l[0].items()}]
结果将是:
[{'point1': [20, 15, 20],
'point2': [0, 34, 8],
'point3': [12, 15, 2],
'point4': [15, 5, 16]}]
array=[{'point1': ['20.900', '15.300', '20.400'], 'point2': ['0.600', '34.700', '8.100'], 'point3': ['12.100', '15.800', '2.300'], 'point4': ['15.000', '5.800', '16.900']}]
new_array=array[0]
for i in new_array.values():
k=0
for j in i:
i[k]=int(float(j))
k=k+1
print(new_array)
a similar question 已经问过了! 你也可以这样做:
arr = [{
'point1': ['20.900', '15.300', '20.400'],
'point2': ['0.600', '34.700', '8.100'],
'point3': ['12.100', '15.800', '2.300'],
'point4': ['15.000', '5.800', '16.900'],
}]
[{k : list(map(float, v)) for k, v in point.items() } for point in arr]