-1

I'm trying iterate over lists in Python, but can't do it in an economic and pythonic way.

I can do in one dimension list:

api_time = ['hour', 'time']

text = 'What time is it?'
request = [r for r in api_time if r in text]

This outputs 'time', which is correct.


But when I start using two dimension list, I can't do it in one sentence.

api_time = ['hour', 'time']
api_weather = ['clime', 'rain']

apis = [api_time, api_weather]

How can I check this in one sentence?

Denis Callau
  • 286
  • 3
  • 12

1 Answers1

2

You can use a double list comprehension:

>>> api_time = ['hour', 'time']
>>> api_weather = ['clime', 'rain']
>>>
>>> apis = [api_time, api_weather]
>>> text = 'What time is it?'
>>> [r for api in apis for r in api if r in text]
['time']

Or a simple list addition instead of nested lists:

>>> [r for r in api_time + api_weather if r in text]
['time']
Eric Duminil
  • 50,694
  • 8
  • 64
  • 113