【问题标题】:Python - List search repeats Not matched?Python - 列表搜索重复不匹配?
【发布时间】:2014-11-22 22:09:09
【问题描述】:

在这个 python 程序中,我试图在排序列表中实现搜索。

我面临的问题很简单,但我无法解决。我想打印元素,当找到元素时,当找不到元素时,我想打印“不匹配”。但问题在于,如果 所选元素 == sorted_list[i],它会打印“不匹配”的每个元素。我不想得到这个。如果我要查找的元素不在列表中,我想获得一次“不匹配”。

这里是代码。

for i in range(0, len(sorted_list)):
    if take_input == sorted_list[i]:
        print sorted_list[i]
    elif take_input != sorted_list[i]:
        print "Not Matched"

【问题讨论】:

  • 你知道for item in sorted_list:吗?还有if take_input in sorte_list:?

标签: python list sorting python-2.7 search


【解决方案1】:

您可以将for ... else ...break 语句一起使用:

for i in range(0, len(sorted_list)):
    if take_input == sorted_list[i]:
        print sorted_list[i]
        break  # get out of the for loop.
else:
    # This will be executed only if the `for` loop is not terminated with `break`.
    print "Not Matched"

如果使用in operator,则不需要迭代:

if take_input in sorted_list:
    print take_input
else:
    print "Not Matched"

顺便说一句,如果不需要索引,只需迭代序列即可,而不是使用索引。

【讨论】:

    【解决方案2】:

    使用in 来检查take_input 是否在sorted_list 中,避免需要遍历sorted_list

    if take_input in sorted_list:
        print take_input
    else:
        print "Not Matched"
    

    你不需要使用 range 来迭代 sorted_list 你可以使用:

    for  i in sorted_list:
        if  i == take_input
    

    如果你想要索引你应该使用enumerate:

    for ind, ele in enumerate(sorted_list): # ind is each index, ele each each element in the list
        if take_input == sorted_list[ind]:
    

    【讨论】:

      【解决方案3】:

      它可以这样工作。 (开关)

      switch_found = 0
      
      for i in range(0, len(sorted_list)):
          if take_input == sorted_list[i]:
              switch_found = 1
              break
      # else it will continue 
      
      if switch_found == 1:
          print sorted_list[i]
      else:
          print "Not Matched"
      

      这将确保它只打印一次找到的元素。如果 switch 未设置为 1,则表示该元素不存在,并且将打印“不匹配”(一次)。

      【讨论】:

        猜你喜欢
        • 2016-08-31
        • 1970-01-01
        • 2017-05-10
        • 1970-01-01
        • 2017-09-12
        • 1970-01-01
        • 1970-01-01
        • 2021-07-11
        • 2014-05-27
        相关资源
        最近更新 更多