找到你要的答案

Q:How to return a value from tuple

Q:如何从元组返回值

Okay, so say I have a tuple like this

values = ('1', 'cat', '2', 'bat', '3', 'rat', '4', 'hat', '5', 'sat')

What loop function would I have to write to ask for a user input for the integer and have it return the word. ie. user inputs 1 and it returns cat. or user inputs 123 and it returns catbatrat (i dont need the output to be have spaces)

edit: I know it would make more sense to use a dictionary, but in this instance, i would not like to.

my code:

    values = ('1', 'cat', '2', 'bat', '3', 'rat', '4', 'hat', '5', 'sat')
    message = raw_input("Enter a number for the corresponding word: ")
    for char in message:
        print values

好吧,说我有这样一个元组

values = ('1', 'cat', '2', 'bat', '3', 'rat', '4', 'hat', '5', 'sat')

我需要写什么循环函数来请求一个整数的用户输入并返回这个单词。如用户输入1,则返回的猫。或用户输入123,则返回catbatrat(我不需要输出要有空格)

编辑:我知道使用字典会更有意义,但在这种情况下,我不喜欢。

我的代码:

    values = ('1', 'cat', '2', 'bat', '3', 'rat', '4', 'hat', '5', 'sat')
    message = raw_input("Enter a number for the corresponding word: ")
    for char in message:
        print values
answer1: 回答1:

As you say, this is much better done via dictionary. But since you insist: you can look up the index for the number in the tuple, and then print the element at the next index:

for char in message:
    print values[values.index(char)+1],

With input '123', will print:

cat bat rat

Note that this will fail horribly if any of the characters entered aren't present since the index method will raise an exception.

I'm wondering if you just want to know how to access individual tuple elements; you can index them just like you would a list. For example, given:

values = ('cat', 'rat', 'bat', 'hat')

You could just say values[0] to get 'cat', for example.

正如你所说,这是更好地完成通过字典。但既然你坚持:你可以在元组中查找索引的编号,然后在下一个索引中打印元素:

for char in message:
    print values[values.index(char)+1],

输入“123”,将打印:

cat bat rat

注意这将不可怕如果输入的字符不存在,因为指数的方法将抛出一个异常。

我不知道你是否只是想知道如何访问单个元组元素,你可以索引他们就像你会一个列表。例如,给定:

values = ('cat', 'rat', 'bat', 'hat')

你可以说值[ 0 ]得到'猫',例如。

python  list  for-loop  while-loop  tuples