这就是我必须为这个问题做的,我不确定格式。这是基于python 3.4的,所以不能使用f‘字符串。
这就是问题所在:
创建一个函数,该函数接受一个字典作为参数,并返回一个包含城市相关事实的字符串。城市事实将需要从字典中提取三个属性:
name
population
continent字符串的格式应该如下:X的人口为Y,位于Z中(其中X是城市名称,Y是人口,Z是城市所在的大陆)。示例
city_facts({
name: "Paris",
population: "2,140,526",
continent: "Europe"
}) ➞ "Paris has a population of 2,140,526 and is situated in Europe"
city_facts({
name: "Tokyo",
population: "13,929,286",
continent: "Asia"
}) ➞ "Tokyo has a population of 13,929,286 and is situated in Asia"*这是我最初想出的方法,但它不起作用,因为Python3.4不存储字典值的顺序。
def city_facts(city):
info = list(city.values())
return '{} has a population of {} and is situated in {}'.format(info[0], info[2], info[1])如何根据字典值填充空格?上面的代码无法工作,因为python3.4不存储字典值的顺序。基于Python3.4,我需要做些什么来解决这个问题?
发布于 2020-07-01 06:13:59
您可以使用如下键直接访问字典
city = {"name": "Paris", "population": "2,140,526", "continent": "Europe"}
def city_facts(city):
return "{} has a population of {} and is situated in {}".format(
city["name"], city["population"], city["continent"]
)
print(city_facts(city))输出:
Paris has a population of 2,140,526 and is situated in Europe发布于 2020-07-01 06:16:57
您可以在str.format中使用关键字参数
city = {"name": "Paris", "population": "2,140,526", "continent": "Europe"}
print("{name} has a population of {population} and is situated in {continent}".format(**city))打印:
Paris has a population of 2,140,526 and is situated in Europe发布于 2020-07-01 06:30:07
也许这段代码可以帮助你。我将你的字典解构成一个列表,然后我做一个映射函数,让每个字典都有一个字符串。这是代码。
city_facts = [{
"name": "Paris",
"population": "2,140,526",
"continent": "Europe"
},
{
"name": "Tokyo",
"population": "13,929,286",
"continent": "Asia"
}]
# im not sure what version of python able to use format string like below
result = list(map(lambda data: f'{data["name"]} has a population of {data["population"]} and is situated in {data["continent"]}', city_facts))
# you can also use this format string for your version python 3.4
result = list(map(lambda data: '{} has a population of {} and is situated in {}'.format(data["name"],data["population"],data["continent"]), city_facts))
# the result will be a list type, if you want to print as a single string, you can make an iteration to the list
print(result)https://stackoverflow.com/questions/62666804
复制相似问题