This is a homework question, I got the basics down, but I can't seem to find the correct method of searching two parallel arrays.

这是一个家庭作业的问题,我已经掌握了基本知识,但是我似乎找不到搜索两个并行数组的正确方法。

Original Question: Design a program that has two parallel arrays: a String array named people that is initialized with the names of seven people, and a String array named phoneNumbers that is initialized with your friends' phone numbers. The program should allow the user to enter a person's name (or part of a person's name). It should then search for that person in the people array. If the person is found, it should get that person's phone number from the phoneNumbers array and display it. If the person is not found, program should display a message indicating so.

最初的问题:设计一个有两个并行数组的程序:一个名为people的字符串数组,用7个人的名字初始化;一个名为phoneNumbers的字符串数组,用朋友的电话号码初始化。这个程序应该允许用户输入一个人的名字(或者一个人名字的一部分)。然后它应该在people数组中搜索那个人。如果找到此人,它应该从phoneNumbers数组中获取此人的电话号码并显示出来。如果没有找到此人,程序应该显示一条这样的消息。

My current code:

我现在的代码:

# 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"]

Now, my entire problem begins here. How do I conduct a search (or partial search) on a name, and return the index of the persons name in the people array and print the phone number accordingly?

现在,我的整个问题从这里开始。如何对名称进行搜索(或部分搜索),并返回人员数组中人员名称的索引并相应地打印电话号码?

Update: I added this to the bottom of the code in order to conduct the search.

更新:我将此添加到代码的底部,以便进行搜索。

lookup = dict(zip(people, phoneNumbers))
if person in lookup:
    print "Name: ", person ," \nPhone:", lookup[person]

But this only works for full matches, I tried using this to get a partial match.

但这只适用于完全匹配,我尝试使用这个来获得部分匹配。

[x for x in enumerate(people) if person in x[1]]

But when I search it on 'tim' for example, it returns [(5, 'timmy')]. How do I get that index of 5 and apply it in print phoneNumbers[the index returned from the search]?

但当我在“tim”上搜索时,它会返回[(5,“timmy”)]。如何获得5的索引并将其应用于print phoneNumbers(搜索返回的索引)?

Update 2: Finally got it to work perfectly. Used this code:

更新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."

2 个解决方案

#1


6

Since this is homework, I'll refrain from giving the code outright.

既然这是家庭作业,我就不直接给出代码了。

You can create a dict that works as a lookup table with the name as the key and the phone number as its value.

您可以创建一个命令,该命令作为查找表使用名称作为键,电话号码作为其值。

Creating the lookup table:

You can easily convert the parallel arrays into a dict using dict() and zip(). Something along the lines of:

您可以很容易地将并行数组转换为使用dict()和zip()的命令。类似于:

lookup = dict(zip(people, phoneNumbers))

To see how that works, have a look at this example:

要了解这是如何工作的,请看这个例子:

>>> people = ["john", "jacob", "bob"]
>>> phoneNumbers = ["5503942", "8659392", "8659392"]
>>> zip(people, phoneNumbers)
[('john', '5503942'), ('jacob', '8659392'), ('bob', '8659392')]
>>> dict(zip(people, phoneNumbers))
{'jacob': '8659392', 'bob': '8659392', 'john': '5503942'}

Finding if a person exist:

You can quickly figure out if a person (key) exist in the lookup table using:

您可以使用以下方法快速判断查找表中是否存在人员(键):

if name in lookup:
    # ... phone number will be lookup[name]

List of people whose name matches substring:

This answer should put you on the right track.

这个答案应该会让你走上正确的道路。

And of course, if the search returns an empty list there are no matching names and you can display an appropriate message.

当然,如果搜索返回一个空列表,则没有匹配的名称,您可以显示适当的消息。


Alternative suggestion

Another approach is to search the list directly and obtain the index of matches which you can then use to retrieve the phone number.

另一种方法是直接搜索列表并获取匹配的索引,然后可以使用该索引检索电话号码。

I'll offer you this example and leave it up to you to expand it into a viable solution.

我将为您提供这个示例,并将其扩展为一个可行的解决方案。

>>> people = ["john", "jacob", "bob", "jacklyn", "cojack", "samantha"]
>>> [x for x in enumerate(people) if "jac" in x[1]] 
[(1, 'jacob'), (3, 'jacklyn'), (4, 'cojack')]

If you hit a snag along the way, share what you've done and we'll be glad to assist.

如果你遇到困难,分享你所做的,我们很乐意帮助你。

Good luck, and have fun.

祝你好运,玩得开心。


Response to updated question

Note that I've provided two alternative solutions, one using a dict as a lookup table and another searching the list directly. Your updates indicate you're trying to mix both solutions together, which is not necessary.

注意,我已经提供了两种替代解决方案,一种是使用dict用作查找表,另一种是直接搜索列表。您的更新表明您正在尝试将两个解决方案混合在一起,这是不必要的。

If you need to search through all the names for substring matches, you might be better off with the second solution (searching the listdirectly). The code example I provided returns a list (since there may be more than one name that contain that substring), with each item being a tuple of (index, name). You'll need to iterate throught the list and extract the index and name. You can then use the index to retrieve the phone number.

如果您需要搜索子字符串匹配的所有名称,那么您最好使用第二个解决方案(搜索列表直接)。我提供的代码示例返回一个列表(因为可能有多个包含该子字符串的名称),每个项都是(index, name)的一个元组。您需要遍历列表并提取索引和名称。然后可以使用索引来检索电话号码。

To avoid just giving you the solution, here's related example:

为了避免给你答案,这里有一个相关的例子:

>>> people = ["john", "jacob", "bob", "jacklyn", "cojack", "samantha"]
>>> matches = [x for x in enumerate(people) if "jac" in x[1]]
>>> for index, name in matches:
...     print index, name
... 
1 jacob
3 jacklyn
4 cojack
>>> matches = [x for x in enumerate(people) if "doesnotexist" in x[1]]
>>> if not matches:
...     print "no matches"
... 
no matches

更多相关文章

  1. 具有1位条目的numpy布尔数组
  2. python编程之一:使用网格索引算法进行空间数据查询
  3. 将2d数组数据视为定义形状的像素——是否可能创建内部和表面?
  4. 从字典中创建NumPy数组的最佳方法是什么?
  5. c++与python关于二维数组的数据传递问题,刚注册没有分,以后一定补
  6. 对numpy数组的每n个元素求平均值
  7. [置顶] Python + C/C++ 嵌入式编程(1):多维数组Numpy.Array(
  8. 堆和索引堆的python实现
  9. 第四章 当索引不好用时

随机推荐

  1. Android 7.0 如何去掉灭屏动画
  2. android wifi hotspot
  3. ViewPager做出广告轮播特效
  4. 深入理解Notification机制
  5. listView分割线
  6. Android(安卓)UI编程之自定义控件初步(上)
  7. android aidl(android studio)
  8. 【Android开发】- HelloWorld
  9. AT91G45——Android2.2移植补丁
  10. 知识点笔记