これは宿題の質問です。基本は理解しましたが、2 つの並列配列を検索する正しい方法が見つからないようです。
元の質問: 2 つの並列配列を持つプログラムを設計します。7 人の名前で初期化される配列 namedString
と、友人の電話番号で初期化される配列 named です。プログラムは、ユーザーが個人の名前 (または個人の名前の一部) を入力できるようにする必要があります。次に、配列内でその人物を検索する必要があります。その人物が見つかった場合、配列からその人物の電話番号を取得して表示する必要があります。人が見つからない場合、プログラムはそのことを示すメッセージを表示する必要があります。people
String
phoneNumbers
people
phoneNumbers
私の現在のコード:
# create main
def main():
# take in name or part of persons name
person = raw_input("Who are you looking for? \n> ")
# convert string to all lowercase for easier searching
person = person.lower()
# run people search with the "person" as the parameters
peopleSearch(person)
# create module to search the people list
def peopleSearch(person):
# create list with the names of the people
people = ["john",
"tom",
"buddy",
"bob",
"sam",
"timmy",
"ames"]
# create list with the phone numbers, indexes are corresponding with the names
# people[0] is phoneNumbers[0] etc.
phoneNumbers = ["5503942",
"9543029",
"5438439",
"5403922",
"8764532",
"8659392",
"9203940"]
今、私の問題全体がここから始まります。名前で検索 (または部分検索) を実行し、 people 配列の人の名前のインデックスを返し、それに応じて電話番号を出力するにはどうすればよいですか?
更新:検索を実行するために、これをコードの最後に追加しました。
lookup = dict(zip(people, phoneNumbers))
if person in lookup:
print "Name: ", person ," \nPhone:", lookup[person]
しかし、これは完全一致でのみ機能します。これを使用して部分一致を取得しようとしました。
[x for x in enumerate(people) if person in x[1]]
しかし、'tim'
たとえば検索すると、 が返されます[(5, 'timmy')]
。そのインデックスを取得して、検索から返されたインデックスに5
適用するにはどうすればよいですか?print phoneNumbers[
]
更新 2:ついに完全に動作するようになりました。このコードを使用しました:
# conduct a search for the person in the people list
search = [x for x in enumerate(people) if person in x[1]]
# for each person that matches the "search", print the name and phone
for index, person in search:
# print name and phone of each person that matches search
print "Name: ", person , "\nPhone: ", phoneNumbers[index]
# if there is nothing that matches the search
if not search:
# display message saying no matches
print "No matches."