简体   繁体   English

python中的这个简单功能无法正常工作

[英]this simple function in python doesn't work properly

I have some problems with these lines of program. 这些程序行有一些问题。 I'm writing a function in python that takes a list of lists and a string as input and returns "the name is here" if the second element of a list in the list of lists is equal to the string given. 我正在用python编写一个函数,该函数将一个列表列表和一个字符串作为输入,如果列表列表中列表的第二个元素等于给定的字符串,则返回“名称在这里”。 In this case the list of list I have is this 在这种情况下,我的清单清单是这个

railway = [["Milan","Zurich"],["Zurich","Bern"],["Bern","Berlin"],["Berlin","Copenaghen"]] 

my function is: 我的功能是:

def travel( list , stringdestination):
        i = 0
    for elemento in range(len(list)):
      if list[i][1] == stringdestination:
          print "target reached"   

when I run: 当我跑步时:

travel(railway, "Bern") 

it should display: "target reached" but it doesn't, it doesn't show anything, why? 它应该显示:“已达到目标”,但是没有,什么也没有显示,为什么?

You are never incrementing i. 你永远不会增加我。 Your loop should be: 您的循环应为:

for pair in list:
    if pair[1] == stringdestination:
        print "target reached"

As it's been answered, you're not incrementing the loop variable. 正如已经回答的那样,您不会增加循环变量。 But that's what's wrong trivially, more importantly, you're coming at this screw like a man with only a hammer in his toolbox. 但这就是平凡的错误,更重要的是,您遇到的是一个螺丝钉,就像一个在工具箱中只有铁锤的人一样。 This is pretty much the exact reason the data structure called dictionary was made. 这几乎就是创建称为字典的数据结构的确切原因。 It's a built in. 这是内置的。

Read up on this, it's much easier and nicer. 阅读有关此内容,它会变得更加容易和友好。 http://www.tutorialspoint.com/python/python_dictionary.htm http://www.tutorialspoint.com/python/python_dictionary.htm

A few points: 几点:

  1. Don't use list as a variable name. 不要将list用作变量名。 list is a built in name list是内置名称
  2. Iterate lists directly for i in mylist 直接for i in mylist列表迭代
  3. It is possible to 'unpack' the pairs in your list by assigning to 2 variables in the iteration 通过在迭代中分配2个变量,可以“解包”列表中的对

For example: 例如:

def travel(places, destination):
    for start, dest in places:
        if destination == dest:
            print "target reached"
            break

It is likely you want to stop iterating when you find the destination. 找到目的地后,您可能想停止迭代。 Do so either by returning immedately from the function or breaking and not returning anything (if no return in a function it implicitly returns None ). 通过从函数立即返回或中断而不返回任何内容来执行此操作(如果函数中没有return ,则隐式返回None )。

I would wrap it in a function , so I stop when a founded the right string. 我会将其包装在一个function ,所以当建立正确的字符串时,我会停下来。 It prevents from looping through the whole list: 它防止遍历整个列表:

def arrived(s, raileway):
    for r in railway:
        if r[1] == s:
            return True
    return False

if arrived("Bern", railway):
    print("target reached")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM