我有一个字典列表如下:
list = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
如何将列表中每个字典内的值转换为整数/浮点数?
这样就变成了:
list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ]
我有一个字典列表如下:
list = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
如何将列表中每个字典内的值转换为整数/浮点数?
这样就变成了:
list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ]
我们必须爱上列表推导式。
[dict([a, int(x)] for a, x in b.items()) for b in list]
(注意:对于仅适用于Python 2的代码,您可以使用"iteritems"代替"items")
for sub in the_list:
for key in sub:
sub[key] = int(sub[key])
将其强制转换为整数而不是字符串。
for item in list_of_dicts:
for key, value in item.iteritems():
try:
item[key] = int(value)
except ValueError:
item[key] = float(value)
>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]
int
、float
和空字符串值,我会使用列表推导式、字典推导式以及条件表达式的组合,如下所示:dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
{'d': '4' , 'e': '5' , 'f': '6'}]
print [{k: int(v) if v and '.' not in v else float(v) if v else None
for k, v in d.iteritems()}
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
然而,字典推导在Python 2中直到2.7版本才被添加。在早期版本中仍然可以作为单个表达式完成,但必须使用dict
构造函数编写,如下所示:
# for pre-Python 2.7
print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
for k, v in d.iteritems())
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
if
表达式来像我在修订后的答案中所示一样处理它们。 - martineauint(x)
替换为类似于我的条件表达式,以摆脱字典推导并得到适用于早期Python版本的结果。 - martineau newlist = [] # Make an empty list
for i in list: # Loop to hv a dict in list
s = {} # Make an empty dict to store new dict data
for k in i.keys(): # To get keys in the dict of the list
s[k] = int(i[k]) # Change the values from string to int by int func
newlist.append(s) # To add the new dict with integer to the list
def number(a, just_try=False):
try:
# First, we try to convert to integer.
# (Note, that all integers can be interpreted
# as float and hexadecimal numbers.)
return int(a)
except:
# The order of the following conversions doesn't matter.
# The integer conversion has failed because `a`
# contains hexadecimal digits [x,a-f] or a
# decimal point ['.'], but not both.
try:
return int(a, 16)
except:
try:
return float(a)
except:
if just_try:
return a
else:
raise
# The conversion:
[dict([a, number(x)] for a, x in b.items()) for b in list]
这将处理整数、浮点和十六进制格式。
list = [ { 'a':1 , 'b':2 , 'c':3 }}, { 'd':4 , 'e':5 , 'f':6 } ]
修正为list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ]
。 - Paolo