【问题标题】:Searching for a string value in a list在列表中搜索字符串值
【发布时间】:2021-03-02 12:18:57
【问题描述】:

我的列表是 a=['Name','Age','Subject'],我想搜索用户的输入是否存在于这个列表中。

假设用户输入 x='name',我如何在这个列表 a 中搜索 x(不区分大小写)?

【问题讨论】:

  • 这能回答你的问题吗? Is there a short contains function for lists?
  • x in list 区分大小写。 x.casefold() in list 不区分大小写。
  • @Shadowcodder 否,仅当 list 中的项目也折叠起来时。该示例大小写不一。

标签: python string list search


【解决方案1】:

如果您想在列表中进行区分大小写的搜索,您可以这样做,

x = "name" # input from the user
l = ['Name','Age','Subject']

if x in l:
    print("Found a match")
else:
    print("No match")

如果您想在列表中进行不区分大小写的搜索,您可以这样做,

x = "name" # input from the user
l = ['Name','Age','Subject']

if x.lower() in list(map(lambda x: x.lower(), l)):
    print("Found a match")
else:
    print("No match")

【讨论】:

    【解决方案2】:

    您可以在不强制转换整个列表的情况下执行以下操作:

    b = input("please enter a string:")
    ismatch =b.title() in a
    print(ismatch)
    
    >>> please enter a string:
    >Age
    >>> True
    

    【讨论】:

      【解决方案3】:

      我认为以下代码可能会对您有所帮助。你要string修改方法lower()/upper()。我在这里使用了lower,它将每个字符的任何大小写都更改为小写。例如使用'NaMe'.lower()NaMe 后更改为“名称”。我更改了输入字符串和列表元素,并检查了输入是否在列表中。就是这样。

      代码

      a=['Name','Age','Subject'] 
      a = [a.lower() for a in a]
      user_input = input("Put the input: ").lower()
      if user_input in a:
          print("Match")
          
      else:
          print("Mismatch")
      

      输出

      > Put the input: AGE
      > Match
      

      【讨论】:

        【解决方案4】:
        a=['Name','Age','Subject']
        if 'Name' in a:
            print "yes"
        

        【讨论】:

          【解决方案5】:

          也许这就是你需要的:

          a = ['Name','Age','Subject']
          x = input('').title()
          b = x in a
          print(b)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多