【问题标题】:How to find an item in a list (without using "in" method)?如何在列表中查找项目(不使用“in”方法)?
【发布时间】:2016-10-20 00:58:18
【问题描述】:

我试图在不使用“in”方法的情况下在列表中查找项目。我尝试使用循环来做到这一点。代码成功执行,但给出了两者的集体结果(找到的项目以及未找到的项目)。我尝试使用 break 语句修复它。它以某种方式起作用。但仍然没有得到预期的结果。

python3.2写的代码是:-

list=[]
item=""
while item!='DONE':
    item=input("Enter the number, To discontinue enter 'DONE': ")

    if item.isdigit():
        item=int(item)
        list.append(item)
    else:
        list.append(item)

del list[-1]
print("The list is: ",list)

num=int(input("Enter the number you want to search in list: "))
def search(list,num):
    for i in range(len(list)):
        if list[i]==num:
            print("Item found")
            break
        else:
            print("Not found")
    return
search(list,num)

请建议我如何修改它以搜索“整数”和“字符串”类型的元素。我的代码适用于整数类型元素。

【问题讨论】:

  • 你为什么不想使用in
  • 我正在尝试寻找替代选项,因为这是我在 python 中的学习阶段。
  • list.index(element) 将返回它在列表中找到的第一个元素的索引,否则引发ValueError。是你要找的吗?
  • 不,实际上我正在尝试检查一个元素是否存在于列表中?
  • 既然开始了,我建议你不要使用list作为变量名,因为内置函数list会被屏蔽,这可能是一个危险的习惯。此外,当您提出问题时,您应该始终尝试发布预期结果以及您得到的结果,尤其是当您遇到错误时。

标签: python list python-3.x search


【解决方案1】:

使用:

def seach(l, elm):
    try:
        l.index(elm)
        print "found"
    except:
        print "not found"

它比自定义循环更 Pythonic。

PS : 当你处于学习阶段时,不要试图找到执行任务的方法。 'in' 关键字就是为此而生的。

【讨论】:

    【解决方案2】:

    由于这是一个学习练习,我将把它作为搜索提交,避免使用in。其他人会声称这是一个肮脏的烂骗子。为什么?

    def search(inlist, item):
        print(item, end="")
        if inlist.__contains__(item):
            print(" found")
        else:
            print(" not found")
    
    mylist = []
    item = None
    while item != 'DONE':
        item = input("Enter the number, To discontinue enter 'DONE': ")
        mylist.append(item)
    
    while True:
        num = input("Enter the item you want to search for: ")
        search(mylist, num)
    

    。 .

    同样本着学习的精神,这里有一个使用集合的解决方案。如果我们使用集合,我们可能一开始就不会费心创建一个列表,但我们假设该列表来自其他地方。

    这里的重点是,如果您有一个大列表和大量搜索,那么使用集合可能比遍历列表更快。

    def search(inset, item):
        print(item, end="")
    
        if inset & set((item,)):
            print(" found")
        else:
            print(" not found")
    
    mylist = []
    item = None
    while item != 'DONE':
        item = input("Enter the number, To discontinue enter 'DONE': ")
        mylist.append(item)
    
    myset = set(mylist)
    while True:
        num = input("Enter the item you want to search for: ")
        search(myset, num)
    

    【讨论】:

      【解决方案3】:

      当您执行此操作时,您正在尝试将字符串转换为 int

      num = int(input("Enter the number you want to search in list: "))
      

      当输入不是数字时,这将引发异常。

      相反,您为什么不直接使用isdigit() 执行您在代码的第一部分中所做的相同操作?如果是数字,则将其转换为int,如果不是数字,则将其保留为字符串。那么你的代码也应该适用于非数字。

      num = input("Enter the number you want to search in list: ")
      if num.isdigit():
          num = int(num)
      

      或者,第二种解决方案是不要在代码的第一部分或第二部分将任何内容转换为int。所以换句话说,将所有内容都保留为字符串,即

      while item != 'DONE':
          item = input("Enter the number, To discontinue enter 'DONE': ")
          list.append(item)
      
      ...
      
      num = input("Enter the number you want to search in list: ")
      

      【讨论】:

      • 对,这里不用检查类型。
      • @leekaiinthesky 不,它没有......我尝试了这段代码,但不适用于整数,(适用于字符串)。不知道我在这里错过了什么??? :-list=[12,45,63,"asd",458,1,"sdr",104] print(list) item=input("在列表中输入要搜索的项目:") def search(list ,item): for i in range(len(list)): if list[i]==item: print("Item found") break else: print("Not found") return search(list,item)跨度>
      • 对,您必须在代码的两个部分都转换为int,或者您必须在代码的任何部分都转换为int。您是否尝试过我在上面所做的替换?
      • @AmritanshuVerma 在您在评论中发布的代码中,您的列表包含ints 和字符串。如果它们仅包含 ["12", "45", "63", "asd", "458", "1", "sdr", "104"] 中的字符串,则无需类型检查就可以了。
      【解决方案4】:

      实际上没有必要区分整数和字符串——它们都是,Python 可以用同样的方式处理在这种情况下。鉴于这一事实,您可以按照以下几行重写您的代码(其中包括您可以用来简化逻辑并以更标准的方式组织代码的其他几种技术——请参阅PEP 8 - Style Guide for Python Code):

      def search(a_list, value):
          for item in a_list:  # note: no need to use an index to iterate a list
              if item == value:
                  print("Value found")
                  break
          else:  # only executes if loop finishes without break
              print("Value not found")
      
      my_list = []  # note: avoid using the names of built-ins like "list"
      while True:
          value = input("Enter an value, to discontinue enter 'DONE': ")
          if value == 'DONE':
              break
          my_list.append(value)
      
      print("The list is: ", my_list)
      
      value = int(input("Enter the value you want to search for in the list: "))
      search(my_list, value)
      

      【讨论】:

        猜你喜欢
        • 2011-01-05
        • 2023-03-11
        • 1970-01-01
        • 2016-06-09
        • 2014-10-10
        • 2014-08-10
        • 1970-01-01
        • 2022-11-21
        • 1970-01-01
        相关资源
        最近更新 更多