Find A Substring
Solution 1:
Oh, I got it. I missunderstood your question. This will be work.
print([v for k, v in capitals.items() if k in v])
# more readableprint([capital forstate, capital in capitals.items() ifstate in capital])
This will return
['Indianapolis', 'Oklahoma City']
Solution 2:
If would go for the following:
states = capitals.keys()
capitals = capitals.values()
solution = [capital for capital in capitals if [state for state in states if state in capital]]
# solution = ['Indianapolis', 'Oklahoma City']
The inner list contains the list of states that appear in the capital we are currently iterating over in the outer list. If this list is not empty current captial is added to the list of outputs.
You can yield the same results by sequencing the same logic with normal if/for
statements.
Solution 3:
- Use map to find the list of matching capitals.
- filter 'None' entries.
Output:
filter(None, map(lambda state: capitals[state] ifstate in capitals[state] else None, capitals))
Output:
['Oklahoma City', 'Indianapolis']
Solution 4:
You can use list comprehension to do the same thing that you code currently does. This:
result = []
for x in capitals.keys():
if(x in capitals[x]):
result.append(capitals[x])
print(result)
can be converted into a list comprehension just by observation.
result= [capitals[x] for x in capitals.keys() if x in capitals[x]]
print(result)
The above is equivalent to your code. If you don't know list comprehensions, I suggest getting familiar with the concept.
This code calls capitals[x]
twice, so there is yet another improvement possible: iterate over the items
of the dictionary, which is covered in Yuda's answer.
Solution 5:
For Python 2.x:
capital_list = []
for state, capital in capitals.iteritems():
if state.lower() in capital.lower():
capital_list.append(capital)
print(capital_list)
For Python 3.x:
capital_list = []
for state, capital in capitals.items():
if state.lower() in capital.lower():
capital_list.append(capital)
print(capital_list)
Result:
['Indianapolis', 'Oklahoma City']
Post a Comment for "Find A Substring"