0

次のような辞書があります。

{'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)                
4

4 に答える 4

2

値をディクショナリに追加するだけでなく、obj[key] = val最初に値を として保存する必要があるかどうかを確認しますfloatregular 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 

re注:スクリプトの先頭に次の行を追加して 、python 正規表現モジュールをインポートする必要があります。import re

おそらくいくつか0'sを無駄にし1'sていますが、これらを読んでください

  1. Python チュートリアル

  2. Python データ型

  3. Python モジュールのインポート

  4. Python での正規表現 HOWTO

「コードを取得」しようとするのをやめて、問題解決能力とプログラミング能力を向上させようとし始めましょう。

于 2012-11-23T21:29:59.480 に答える
1
s = '12345'
num = int(s) //num is 12345
于 2012-11-23T21:14:13.797 に答える
1

これはあなたの前の質問に基づいていると思います。その場合は、辞書に入れる前に「軌道半径」の値を通知することを検討する必要があります。その投稿に対する私の答えは、実際にあなたのためにこれを行います:

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])

お役に立てれば

于 2012-11-23T21:16:53.553 に答える
0

あなたの例のように、これが1レベルの再帰辞書である場合、次を使用できます。

for i in the_dict:
    for j in the_dict[i]:
        try:
            the_dict[i][j] = int (the_dict[i][j])
        except:
            pass

任意に再帰的である場合は、より複雑な再帰関数が必要になります。あなたの質問はこれに関するものではないようですので、その例は示しません。

于 2012-11-23T21:16:19.463 に答える