Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中打印包含列表名称的嵌套列表?_Python_List_Nested Loops_Nested Lists - Fatal编程技术网

如何在Python中打印包含列表名称的嵌套列表?

如何在Python中打印包含列表名称的嵌套列表?,python,list,nested-loops,nested-lists,Python,List,Nested Loops,Nested Lists,我想打印出嵌套列表结构的内容 以下是我的嵌套列表: usa = ['New York', 'Chicago', 'Seattle'] canada = ['Vancouver', 'Toronto', 'Kelowna'] england = ['London', 'Liverpool', 'Birmingham'] countries = [usa, canada, england] 我希望输出看起来像: 美国:纽约、芝加哥、西雅图, 加拿大:温哥华、多伦多、基洛纳, 英格兰:伦敦、利物

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

以下是我的嵌套列表:

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

countries = [usa, canada, england]

我希望输出看起来像:

美国:纽约、芝加哥、西雅图,
加拿大:温哥华、多伦多、基洛纳,

英格兰:伦敦、利物浦、伯明翰,

这里有一个很酷的简单方法:

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

尝试使用
词典

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

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