仅限 Python 元组打印键名称



有人可以给我一个关于如何打印元组中所有键的名称的提示吗?IE,

拉尔夫 马利 山 姆

例如,我将如何只打印下面每个动物的名称,而不是嵌套键(如果我的术语正确......(,其中列出了动物类型和标识符。

animals = {'ralph': ('dog', 160101),
'marley': ('dog', 160102),
'sam': ('cat', 160103),
'bones': ('dog', 160104),
'bella': ('cat', 160105),
'max': ('dog', 160106),
'daisy': ('cat', 160107),
'angel': ('cat', 160108),
'luna': ('cat', 160109),
'buddy': ('dog', 160110),
'coco': ('dog', 160111),
}
#dict(TUPLE)[key]
d = dict(animals)

for animal in animals.items():
print(animal)

不确定你在尝试什么。一口气想通了。

>>> for name, animal in animals.items():
...     animal_type, the_number = animal
...     print(f'The {animal_type} {name} has the number {the_number}')
...
The dog ralph has the number 160101
The dog marley has the number 160102
The cat sam has the number 160103
The dog bones has the number 160104
The cat bella has the number 160105
The dog max has the number 160106
The cat daisy has the number 160107
The cat angel has the number 160108
The cat luna has the number 160109
The dog buddy has the number 160110
The dog coco has the number 160111
>>>

这里有两件基本的事情:

  1. dict.items()从字典中生成键和值
  2. a, b = c将元组c = (0, 0)"解压缩"为名称ab,如a = c[0]b = c[1](元组必须正好有两个值(

另外值得一提的是,如果您需要字典键(而不是值或两者(,.keys()会生成字典中的每个键。.values()做同样的事情,但对于值。

有人可以给我一个关于如何打印元组中所有键的名称的提示吗?

您的animals变量是dict,而不是tuple。它的值是元组。所以你的问题实际上是"我如何打印字典的键",这很简单:

print(animals.keys())

或者,如果您希望每行一个:

print("n".join(animals)

或者,如果您真的想要一个 for 循环:

for key in animals: 
print(key)

请注意,我们在最后两个示例中不使用.keys()方法,因为dict是可迭代对象,并且它们在其键而不是值上执行此操作。

您可能想阅读精美的手册(从官方教程开始(以了解有关"术语"(这确实非常重要(以及标准数据类型必须提供的更多信息。

这应该可以做到。

for animal in animals.keys():
print(animal)

你期待这个吗?animals.items()中的每个迭代都包含两个不同的值,即键和元组。您应该通过在循环中添加位置[0]来解决第一个索引中的键。

for animal in animals.items():
print(animal[0])

输出:

ralph
marley
sam
bones
bella
max
daisy
angel
luna
buddy
coco
for key, value in animals.items():
print(key)

首先,你的animals元组实际上已经是一个字典,而不是一个元组。因此,调用dict()是多余的。

此外,字典animals的条目是键/值对的组合,动物的名称作为键,它们的物种和数量作为它们在实际元组中的各自值。

您使用的dict.items()返回元组列表(key, value)您可以像索引列表一样为其编制索引。因此,以下内容应该有效:

animals = {'ralph': ('dog', 160101),
'marley': ('dog', 160102),
'sam': ('cat', 160103),
'bones': ('dog', 160104),
'bella': ('cat', 160105),
'max': ('dog', 160106),
'daisy': ('cat', 160107),
'angel': ('cat', 160108),
'luna': ('cat', 160109),
'buddy': ('dog', 160110),
'coco': ('dog', 160111),
}
for KeyAndValue in animals.items():
print(KeyAndValue[0])

结果在:

ralph
marley
sam
bones
bella
max
daisy
angel
luna
buddy
coco

您也可以通过以下方式仅迭代键:

for name in animals.keys():
print(name)

结果在:

ralph
marley
sam
bones
bella
max
daisy
angel
luna
buddy
coco

请注意,您实际上不必调用dict.keys()方法,因为默认情况下字典可以通过其键进行迭代。 参见Bruno Desthuilliers Answer了解详细信息和示例。

最新更新