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

你的程序有两个问题

  1. 它返回一个空字典{}而不是您创建的字典
  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 回答