除了我的内容之外,是否有更清晰的打印声明?
weather = [{
'day_1': ['Overcast', 87, 20, 'Saturday', 'Chamblee'],
'day_2': ['Rain', 80, 25, 'Sunday', 'Marietta'],
'day_3': ['Sunny', 90, 30, 'Monday', 'Atlanta']
}]
for item in weather:
print(item['day_1'][3], 'in',
item['day_1'][4],
'looks like',
item['day_1'][0],
'with a high of',
item['day_1'][1],
'and a',
item['day_1'][2],
'% chance of rain.')
我需要为每一天的密钥运行这句话。
答案 0 :(得分:4)
print(
'{3} in {4} looks like {0} with a high of '
'{1} and a {2}% chance of rain'.format(*item['day_1']))
占位符编号引用item['day_1']
序列的位置。
答案 1 :(得分:0)
最干净的方法可能是使用单独的函数和字符串格式。
def print_weather(info):
text = "{day}"
" in {place}"
" looks like {weather}"
" with a high of {high}"
" and a {rain}% of rain"
text = text.format(day = info[3],
place = info[4],
weather = info[0],
high = info[1],
rain = info[2])
print(text)
答案 2 :(得分:0)
如果您更好地整理数据,可以将str.format()
与named fields一起使用,例如{location}
,这样可以使您的代码更具可读性:
weather = [
{'forecast': 'Overcast', 'high': 87, 'rain': 20, 'day': 'Saturday', 'location': 'Chamblee'},
{'forecast': 'Rain', 'high': 80, 'rain': 25, 'day': 'Sunday', 'location': 'Marietta'},
{'forecast': 'Sunny', 'high': 90, 'rain': 30, 'day': 'Monday', 'location': 'Atlanta'}
]
for item in weather:
print("{day} in {location} looks like {forecast} with "
"high of {high} and a {rain}% chance of rain.".format(**item))
产地:
Saturday in Chamblee looks like Overcast with high of 87 and a 20% chance of rain.
Sunday in Marietta looks like Rain with high of 80 and a 25% chance of rain.
Monday in Atlanta looks like Sunny with high of 90 and a 30% chance of rain.