【问题标题】:How to print a nested list including the list name in Python? [duplicate]如何在 Python 中打印包含列表名称的嵌套列表? [复制]
【发布时间】:2020-10-22 16:49:42
【问题描述】:

我想打印出嵌套列表结构的内容。

这是我的嵌套列表:

usa = ['New York', 'Chicago', 'Seattle']
canada = ['Vancouver', 'Toronto', 'Kelowna']
england = ['London', 'Liverpool', 'Birmingham']

countries = [usa, canada, england]

我希望输出看起来像:

美国:纽约、芝加哥、西雅图、
加拿大:温哥华、多伦多、基洛纳、
英国:伦敦、利物浦、伯明翰、

【问题讨论】:

  • 你必须做一些非常“hacky”的事情来打印变量的名字,你能把名字硬编码到结构中吗?
  • 这里使用字典,其中字典键是列表名称,它们映射到列表。然后,您可以使用字典的 items 方法进行迭代。

标签: python list nested-loops nested-lists


【解决方案1】:

这是一个很酷的简单方法:

usa = ['New York', 'Chicago', 'Seattle']
canada = ['Vancouver', 'Toronto', 'Kelowna']
england = ['London', 'Liverpool', 'Birmingham']

print("usa: ", *usa)
print("canda: ", *canada)
print("england: ", *england)

#or if you want commas

print("usa: ", ", ".join(usa))
...

【讨论】:

    【解决方案2】:

    尝试使用dictionary

    usa = ['New York', 'Chicago', 'Seattle']
    canada = ['Vancouver', 'Toronto', 'Kelowna']
    england = ['London', 'Liverpool', 'Birmingham']
    
    dictionary = {'usa':usa,
                  'canada':canada,
                  'england':england}
    
    for key in dictionary.keys():
        string = ', '.join(dictionary[key])
        print(f"{key}: {string}")
    

    输出:

    usa: New York, Chicago, Seattle
    canada: Vancouver, Toronto, Kelowna
    england: London, Liverpool, Birmingham
    

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      相关资源
      最近更新 更多