简体   繁体   中英

Print elements in list of tuple of tuple

I have a list of tuples of tuples:

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

I am trying to return all items that match a specific string. So far I have this:

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

This returns:

('germany', 'berlin')

My desired output would be:

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

I have looked at list comprehension in the documentation but I cannot work out how to show the number for each tuple.

The code you are looking for is

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

Since you are a bit confused about the indexing:

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

If you're building that data structure yourself, I'd recommend you to use a more explicit structure, like a dict or a namedtuple.

With your data structure, what you need is:

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

While with a dict, you could have:

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)

Which I personally think it's much easier to read. namedtuple is probably a better structure in this case, but it's slightly more complicated.

The current answer is sufficient, but if you want to check both items in the tuple for the string you could do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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