如何在用户输入提供的列表中查找字符串或字符串的一部分?

时间:2019-04-23 13:01:31

标签: python python-3.x

我正在建立一个显示其统计信息的棒球运动员列表,并且我希望支持通过用户输入进行查询的请求。例如,如果用户想查找一个玩家,而只知道名字的一部分并运行它,那么我写下的代码仍然可以在包含这些字母的列表中找到该玩家。

我似乎找不到for循环和if语句的正确组合。

我尝试了以下代码:

all_players = the list

for player in all_players:
    request_player = input("Please provide the name of the player you want to look up? ")
    if request_player in all_players:
        print(all_players)
    else:
        print("No player with that name was found.")

我希望如果一个球员的名字是Miquel Andujar并且在列表中,那么我应该写下“ miqu”作为输入。我得到所有包含“ miqu”的匹配名称。

但是使用上面的代码,我只会得到“找不到该名称的玩家”。回来。

8 个答案:

答案 0 :(得分:1)

这应该有效。您遍历每个玩家的名称,并检查名称中是否包含request_player,如果包含,请将其附加到列表中,否则说找不到。您还希望在通过in比较之前将所有名称都转换为小写。

all_players = ['John', 'miquel', 'miquila', 'michael']

request_player = input("Please provide the name of the player you want to look up? ")
found = False
names = []
for player in all_players:
    if request_player.lower() in player.lower():
        names.append(player)
        found = True

if found:
    print(names)
else:
    print("No player with that name was found.")

输出将如下所示:

Please provide the name of the player you want to look up? miqu
['miquel', 'miquila']

Please provide the name of the player you want to look up? james
No player with that name was found.

答案 1 :(得分:1)

让我们开始将input(...)移至for循环之外。我们只需要输入一次即可。

all_players = ["the list", "Joe Moped", "Miquel Andujar"]

request_player = input("Please provide the name of the player you want to look up? ")

我们还可以用非常简单的if代替re.search条件。您的正则表达式可能会变得更复杂,但这是一个开始

import re

all_players = ["the list", "Joe Moped", "Miquel Andujar"]

request_player = input("Please provide the name of the player you want to look up? ")
for player in all_players:
    if re.search(request_player.lower(), player.lower()):
        print("Found player: {}".format(player))
        break
    else:
        print("No player with that name was found.")

这是因为如果没有匹配项,re.search将返回None,因此if条件的计算结果为False

对于不太冗长的打印输出,我们可以尝试以下操作:

out = "No player with that name was found."
for player in all_players:
    if re.search(request_player.lower(), player.lower()):
        out = "Found player: {}".format(player)
        print(out)

if out == "No player with that name was found.": print(out)

答案 2 :(得分:0)

dog = ['the','dog','is','good','pool']

user_input='oo'

for i in dog:
    if user_input in i:
        print(i)

这将打印出好消息。

这是与您正在执行的操作类似的示例。您可以直接使用user_input。我只是为了简单起见将其设为“ oo”。而不是查看request_player是否在all_players中,请尝试查看它是否在player中。

答案 3 :(得分:0)

您可能需要简化一些元素。

首先,由于您要遍历all_players,因此它只会询问用户NN = len(all_players)的位置。我怀疑您实际上是希望程序询问一次(或反复询问)。另外,检查用户请求的播放器(或部分名称)是否在列表中的实际过程可能应该做成一个函数。

我建议将您的程序编写为...

all_players = [
    'Barry Bonds',
    'Babe Ruth',
    # and more...
]

# lets define a function that takes a partial name and checks it
def find_player(partial_name, all_players):
    for player_name in all_players:
        # this is the actual matching logic.
        # you can use Regex to get fancy, but this works
        if partial_name in player_name:
            return player_name
    # it wasn't found, technically this line is redundant
    return None

# now loop to ask the user who they're looking for
while True:
    request_player = input("Please provide the name of the player you want to look up? ")
    player_name = find_player(request_player, all_players)
    if player_name
        print(player_name)
    else:
        print("No player with that name was found.")

请注意,上面的示例将仅返回与部分玩家匹配的第一个玩家。因此,如果您键入“ Ba”,它将仅返回all_players中与其匹配的第一个玩家。另外,上面的示例假设名称是类型敏感的,因此键入“ ba”将找不到任何播放器。

答案 4 :(得分:0)

  • 您想在循环外进行查询。
  • 您要检查它是否在特定播放器的名称内,而不是它是否恰好是列表输入的输入。
  • 如果未找到任何内容,则打印出未找到的消息。

    all_players = ['Miquel Andujar', 'abd']
    request_player = input("Please provide the name of the player you want to look up? ")
    request_player = request_player.lower()
    found = False
    for player in all_players:
        if request_player in player.lower():
            print(player)
            found = True
    if not found:
        print("No player with that name was found.")
    

答案 5 :(得分:0)

也许您可以使用列表理解:

matching_players = [matching_player for matching_player in all_players if request_player in matching_players]

答案 6 :(得分:0)

您可以尝试

all_players = ['ashish','neha','riya','rahul']
for player in all_players:
    request_player = input("Please provide the name of the player you want to look up? ")
    if request_player in player:
        print(all_players)
        print(player)
    else:
        print("No player with that name was found.")

答案 7 :(得分:0)

我认为这可以回答您的问题,希望这些评论能说明我所做的事情。 与往常一样,有很多方法可以回答问题!

# I added some names...
all_players = ('Miquel Andujar', 'Jonathan Groves', 'Teresa May', 'Jean-Claude Juncker')
# Use raw_input instead...
request_player = raw_input('Please provide the name of the player you want to look up? ')
# Get a lower-case version of the input string (we'll use lower-case for all string comparisons, but this doesn't
# affect the input list, nor what the user enters):
request_player_lower = request_player.lower()
# Set a flag to be set if we find the player:
found = False
# Loop through players:
for player in all_players:
    # Get a lower-case version of this player:
    player_lower = player.lower()
    # Search for our player name in this lower-case player name:
    if (player_lower.find(request_player_lower) != -1):
        # Found them! Tell human:
        print('Found: ' + player)
        # Set flag
        found = True
# Did we find the player?
if not found:
    # No - Tell human.
    print('Not found.')