Python zip()函数

时间:2014-08-30 08:51:05

标签: python

嗨,大家好我是python编码的新手,我正在练习列表和字典。我有一个代码,其中每个名称都有一个固定的编号,当我输入名称时,他们的编号就会打印出来。

name_list = ["bob","jim","james","julie","june"]
number_list = ["1","2","3","4","5"]
name_and_number = dict(zip(name_list, number_list))

def namenumb(something):
    try:
        print("{}'s number is {}".format(
            something, name_and_number[something]))
    except KeyError:
        print("That name doesn't exist"
            .format(namenumb))


while True:
    word = input("> ")
    namenumb(word)

但是,我希望它能以相反的方式工作,所以当我输入他们名字中的数字时会打印出来。我该怎么办?

由于

3 个答案:

答案 0 :(得分:1)

1)你可以简单地切换你的zip语句的参数并重复相同的

number_and_name = dict(zip(number_list, name_list))
# {'1': 'bob', '3': 'james', '2': 'jim', '5': 'june', '4': 'julie'}

2)另一种方法是使用index()函数

def get_name(number):
    print name_list[number_list.index(number)]

答案 1 :(得分:0)

没有直接的方法可以做到这一点,但还有其他方法可以做到这一点。 首先,您可以遍历dict并测试该值是否为输入的数字。

for key, value in name_and_number.items():
    if value == number:
        print("{}'s number is {}".format(key, value))

第二种方法是使用反转的zip创建另一个dict并以与你相同的方式测试它。

number_and_name = dict(zip(number_list, name_list))

另一种方法是使用index function。有了这个,你可以完全避免拉链。 从名称中获取数字:

print("{}'s number is {}".format(name, number_list[name_list.index(name)]))

从数字中获取名称:

print("{}'s number is {}".format(name_list[number_list.index(number)], number))

答案 2 :(得分:0)

name_list = ["bob","jim","james","julie","june"]
number_list = ["1","2","3","4","5"]
name_and_number = dict(zip(name_list, number_list))

def namenumb(something):
    try:
        for key,value in name_and_number.items():
            if key == something:
                print("{0}'s number is {1}".format(
                                             something, name_and_number[something]))
            elif value == something:
                print("{0}'s name is {1}".format(
                                             something, key))
    except KeyError:
        print("That name doesn't exist"
            .format(namenumb))


while True:
    word = raw_input("> ")
    namenumb(word)

这应该是你要找的代码我猜... dict.items()做的工作.. !!