Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的这个简单函数没有';我不能正常工作_Python_List - Fatal编程技术网

python中的这个简单函数没有';我不能正常工作

python中的这个简单函数没有';我不能正常工作,python,list,Python,List,我对这些程序行有一些问题。我正在用python编写一个函数,该函数将列表和字符串作为输入,如果列表中列表的第二个元素等于给定的字符串,则返回“name is here”。在这种情况下,我的列表如下 railway = [["Milan","Zurich"],["Zurich","Bern"],["Bern","Berlin"],["Berlin","Copenaghen"]] 我的职能是: def travel( list , stringdestination): i =

我对这些程序行有一些问题。我正在用python编写一个函数,该函数将列表和字符串作为输入,如果列表中列表的第二个元素等于给定的字符串,则返回“name is here”。在这种情况下,我的列表如下

railway = [["Milan","Zurich"],["Zurich","Bern"],["Bern","Berlin"],["Berlin","Copenaghen"]] 
我的职能是:

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

travel(railway, "Bern") 

它应该显示:“已达到目标”,但它没有,它没有显示任何内容,为什么?

您永远不会增加i。您的循环应该是:

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

我会将它包装在一个
函数中
,因此当一个函数找到正确的字符串时,我会停止。它防止在整个列表中循环:

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

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

  • 不要将
    list
    用作变量名<代码>列表是一个内置名称
  • 直接迭代mylist中i的列表
  • 通过在迭代中分配给2个变量,可以“解包”列表中的对
  • 例如:

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

    当您找到目的地时,可能希望停止迭代。通过立即从函数返回或中断并不返回任何内容(如果函数中的no
    return
    ,它将隐式返回None)。

    由于它已被回答,因此您不会增加循环变量。但这就是问题所在,更重要的是,你就像一个工具箱里只有一把锤子的人一样,朝这个螺丝钉走去。这就是所谓的dictionary数据结构产生的原因。它是内置的

    仔细阅读这篇文章,它更简单、更好。

    什么时候更新
    i
    ?试着改变它。不要像那样重复列表。对列表中的项目使用
    。不要将列表命名为
    list
    。不要将列表命名为
    list
    。当然,使用内置的任何内容都是否定的,但它们不是保留关键字。我还希望减少与常用变量名称(如列表和类型)的重叠。然后,我建议您更新您的答案,以使用类似于
    my_list
    destination
    或类似的内容作为好的变量名称的示例。但是,应该避免使用运算符模块。它很少使代码更具可读性。我不知道为什么“itemgetter(1)(r)”比“r[0]”更具可读性。@FEdericoSOmaschini,如果您需要对数据进行排序,您可以使用OrderedDict从集合中进行排序:谢谢Kyle,我开始使用字典,但问题是数据没有排序