Python 有没有更干净的方法来打印这份词典列表?
除了我的声明之外,还有更清晰的声明吗Python 有没有更干净的方法来打印这份词典列表?,python,Python,除了我的声明之外,还有更清晰的声明吗 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], '
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.')
我需要为每个日期键运行此句子。使用:
占位符编号引用项目['day_1']
序列的位置。使用:
占位符编号引用
项['day_1']
序列的位置。最干净的方法可能是使用单独的函数和字符串格式
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)
最干净的方法可能是使用单独的函数和字符串格式
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)
如果您能更好地组织数据,您可以使用with,比如
{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.
如果您能更好地组织数据,您可以使用with,比如
{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.
哈哈哈!哦,也很好。几乎神奇地使用了索引,但绝对很酷。哈哈哈!哦,也很好。几乎神奇地使用索引,但绝对很酷。