1

「population.tsv」という.tsvファイルが与えられました。これは、多くの都市の人口を示しています。都市をキーとし、人口をその値とする辞書を作成する必要があります。辞書を作成した後、人口が10,000人未満の都市を削除する必要があります。どうしたの?

def Dictionary():
    d={}
    with open("population.tsv") as f:
        for line in f:
            (key, value)=line.split()
            d[int(key)]=val
    return {}
list=Dictionary()
print(list)
4

1 に答える 1

2

プログラムには2つの問題があります

  1. {}作成したdictの代わりに空のdictを返します
  2. まだフィルター機能を組み込んでいませんI have to eliminate the cities which have less than 10,000 people.
  3. 組み込みの変数に名前を付けないでください

修正されたコード

def Dictionary():
    d={}
    with open("population.tsv") as f:
        for line in f:
            (key, value)=line.split()
            key = int(val)
            #I have to eliminate the cities which have less than 10,000 people
            if key < 10000: 
                d[int(key)]=val
    #return {}
    #You want to return the created dictionary
    return d
#list=Dictionary()
# You do not wan't to name a variable to a built-in
lst = Dictionary()

print(lst)

dictジェネレータ式または単純なdict理解を渡すことによって組み込みを使用することもできることに注意してください(Py 2.7を使用している場合)

def Dictionary():
    with open("population.tsv") as f:
        {k: v for k,v in (map(int, line.split()) for line in f) if k < 10000}
        #If using Py < Py 2.7
        #dict((k, v) for k,v in (map(int, line.split()) for line in f) if k < 10000)
于 2013-02-26T02:09:46.387 に答える