繁体   English   中英

在元组的元组列表中打印元素

[英]Print elements in list of tuple of tuple

我有一个元组的元组列表:

countries = [(('germany', 'berlin'),3),(('england', 'london'),90),(('holland', 'amsterdam'), 43)]

我正在尝试返回与特定字符串匹配的所有项目。 到目前为止,我有这个:

for i in countries:
   if i[0] == 'germany':
      print i

返回:

('germany', 'berlin')

我想要的输出将是:

('germany', 'berlin'),3)

我已经看过文档中的列表理解,但是我不知道如何显示每个元组的数字。

您正在寻找的代码是

for i in countries:
   if i[0][0] == 'germany':
      print i

由于您对索引有点困惑:

i --> (('germany', 'berlin'),3)
i[0] --> ('germany,'berlin')
i[0][0] --> 'germany'

如果您要自己构建数据结构,建议您使用更明确的结构,例如dict或namedtuple。

使用数据结构,您需要的是:

countries = [(('germany', 'berlin'),3),(('england', 'london'),90),(('holland', 'amsterdam'), 43)]
for country in countries:
    if country[0][0]:
        print(country)

使用字典时,您可以:

countries = [{'id': 3,
              'info': {'name': 'germany',
                       'capital': 'berlin'}},
             {'id': 90,
              'info': {'name': 'england',
                       'capital': london}}]
for country in countries:
    if country['info']['name'] == 'germany':
        print(country)

我个人认为这更容易阅读。 在这种情况下, namedtuple可能是更好的结构,但是稍微复杂一些。

当前答案就足够了,但是如果您要检查元组中的两个项目是否都包含该字符串,则可以执行以下操作:

for i in countries:
    if 'germany' in i[0]:
        print i

暂无
暂无

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

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