繁体   English   中英

有没有更干净的方法来打印此词典列表?

[英]Is there a cleaner way to print this list of dictionaries?

除了我拥有的以外,是否还有更清洁的打印说明?

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.')

我需要为每个“日”键运行此语句。

使用字符串格式

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']序列的位置。

最干净的方法可能是使用单独的函数和字符串格式。

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)

如果您更好地组织数据,则可以将str.format()命名字段一起使用 ,例如{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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM