Python 打印函数城市名称

时间:2021-01-19 19:41:12

标签: python list dictionary printing

我正在尝试从此列表字典中打印“Phoenix”,但无法提取特定名称。

test = [{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}, 1000, 2000, 3000, ['hat', 't-shirt', 'jeans', {'socks1': 'red', 'socks2': 'blue'}]]

print(test[0]) 给了我所有的城市名称...我如何只显示“凤凰”?

4 个答案:

答案 0 :(得分:2)

使用 void Main() { string MainPath = "D:\\LAK"; // unless your directory is actually named \LAK:) you should use either @"D:\LAK" or "d:\\LAK" CloneContent(MainPath,1000); } public void CloneContent(string directoryToSearch, int maxrunCount) { if(maxrunCount==0) return; System.Diagnostics.Debug.Print(directoryToSearch); string[] directories = null; try { directories = Directory.GetDirectories(directoryToSearch); } catch(UnauthorizedAccessException ex) { System.Diagnostics.Debug.Print($"No access to dir {directoryToSearch}"); directories = new string[0]; } // ensure you have access to the current directoryToSearch foreach (var directory in directories) { CloneContent(directory,--maxrunCount); } System.Diagnostics.Debug.Print($"cloning {directoryToSearch}"); // .... do the actual cloning here, // you will end up here when there are no more subdirectories on the current branch } 您只是访问列表测试的第一个元素,在本例中是字典。

您需要使用密钥 - 在这种情况下Arizona

test[0]

输出为 print(test[0]['Arizona'])

答案 1 :(得分:0)

您应该阅读一下字典数据结构。但是给你:

Phoenix

答案 2 :(得分:0)

尝试运行以下代码片段,您很可能会得到自己的答案。

test = [{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}, 1000, 2000, 3000,
        ['hat', 't-shirt', 'jeans', {'socks1': 'red', 'socks2': 'blue'}]]

print(test[0]['Arizona'])

for index in range(len(test)):
    print("test[" + str(index) + "]:")
    print(str(test[index]))
    print()

输出将如下所示:

Phoenix
test[0]:
{'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}

test[1]:
1000

test[2]:
2000

test[3]:
3000

test[4]:
['hat', 't-shirt', 'jeans', {'socks1': 'red', 'socks2': 'blue'}]

输出说明 test 是一个包含 5 个元素的数组,第 0 个元素是一个关联数组。因此,要输出 Phoenix,您必须使用 test[0]['Arizona']

答案 3 :(得分:0)

如果只使用 test[0],则只能访问 test 列表中的第一个元素: {'Arizona': 'Phoenix', 'California': 'Sacramento', 'Hawaii': 'Honolulu'}

test[0] 是一本字典。并且您需要获取 'Phoenix' 这是键 'Arizona' 的值,您可以使用该键来获取值: test[0]['Arizona']

相关问题