我收到了一个名为“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)
最佳答案
您的程序有两个问题
- 它返回一个空字典
{}
,而不是您创建的字典 - 你还没加入过滤功能
我得把人口少于10000的城市剔除。
- 不应将变量命名为内置变量
固定代码
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
(如果使用 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)
关于python - 通过.tsv文件创建字典并消除值低于特定数字的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080143/