【发布时间】:2011-12-17 09:00:06
【问题描述】:
这是一道家庭作业题,我已经掌握了基础知识,但我似乎找不到搜索两个并行数组的正确方法。
原问题:设计一个具有两个并行数组的程序:一个名为people 的String 数组以七个人的名字初始化,一个名为@987654324 的String 数组@ 用你朋友的电话号码初始化。该程序应允许用户输入人名(或人名的一部分)。然后它应该在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"]
现在,我的整个问题从这里开始。如何对姓名进行搜索(或部分搜索),并返回人员数组中人员姓名的索引并相应地打印电话号码?
更新:我将此添加到代码底部以便进行搜索。
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."
【问题讨论】:
-
你也许可以建立一个中间字典,def
create_dict(list1,list2): d = {} for i in list1: d.insert(list1[i],list2[i]) return d但像肖恩钦说的那样使用 zip 更有效
标签: python arrays parallel-arrays