我有一本字典,如:
{'Sun': {'Satellites': 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris', 'Orbital Radius': '0', 'Object': 'Sun', 'RootObject': 'Sun', 'Radius': '20890260'}, 'Earth': {'Period': '365.256363004', 'Satellites': 'Moon', 'Orbital Radius': '77098290', 'Radius': '63710.41000.0', 'Object': 'Earth'}, 'Moon': {'Period': '27.321582', 'Orbital Radius': '18128500', 'Radius': '1737000.10', 'Object': 'Moon'}}
我想知道如何将数字值更改为整数而不是字符串。
def read_next_object(file):
obj = {}
for line in file:
if not line.strip(): continue
line = line.strip()
key, val = line.split(": ")
if key in obj and key == "Object":
yield obj
obj = {}
obj[key] = val
yield obj
planets = {}
with open( "smallsolar.txt", 'r') as f:
for obj in read_next_object(f):
planets[obj["Object"]] = obj
print(planets)
答案 0 :(得分:2)
首先检查值是否应存储为obj[key] = val
,而不是仅将值添加到字典float
中。我们可以使用regular expression
匹配来完成此操作。
if re.match('^[0-9.]+$',val): # If the value only contains digits or a .
obj[key] = float(val) # Store it as a float not a string
else:
obj[key] = val # Else store as string
注意:您需要通过将此行添加到脚本顶部来导入python正则表达式模块re
:import re
可能会在这里浪费一些0's
和1's
,但请阅读以下内容:
停止尝试'获取代码'并开始尝试开发解决问题和编程的能力,否则你只会到目前为止......
答案 1 :(得分:1)
s = '12345'
num = int(s) //num is 12345
答案 2 :(得分:1)
我怀疑这是基于your previous question。如果是这种情况,您应该考虑在将“Orbital Radius”放入词典之前对其进行说明。我对该帖子的回答实际上是为你做的:
elif line.startswith('Orbital Radius'):
# get the thing after the ":".
# This is the orbital radius of the planetary body.
# We want to store that as an integer. So let's call int() on it
rad = int(line.partition(":")[-1].strip())
# now, add the orbital radius as the value of the planetary body in "answer"
answer[obj] = rad
但是如果你真的想在创建它之后处理字典中的数字,那么你可以这样做:
def intify(d):
for k in d:
if isinstance(d[k], dict):
intify(d[k])
elif isinstance(d[k], str):
if d[k].strip().isdigit():
d[k] = int(d[k])
elif all(c.isdigit() or c=='.' for c in d[k].strip()) and d[k].count('.')==1:
d[k] = float(d[k])
希望这有帮助
答案 3 :(得分:0)
如果这是一个单级递归字典,如在您的示例中,您可以使用:
for i in the_dict:
for j in the_dict[i]:
try:
the_dict[i][j] = int (the_dict[i][j])
except:
pass
如果是任意递归,则需要更复杂的递归函数。由于您的问题似乎与此无关,因此我不会举例说明。