如何使用正则表达式搜索从多维列表中返回项目

时间:2018-03-29 19:17:54

标签: python regex python-3.x list

我在Python 3中寻求解决问题的帮助: 在多维列表中使用RE模块进行搜索,并在从列表中返回数据块之后

以下是我的例子:

import re

# my search input
my_list = [["10","ten","bottles"],
          ["9","seven","bottles"], 
          ["8","eight","bottles"]]

# search input
def some_input(prompt):
    while True:
        try:
            my_search = int(input(prompt))
        except ValueError:
            print(
                "ERROR: Please enter your account number \
                \nContinue...\n"
                )
        else:
            break
    return str(my_search)

# search for match
def find_my_input():
    search = some_input("Search >>> ")
    regex = re.compile(search)
    for item in my_list:
        new_list = filter(regex.match, my_list)
        if item == new_list: 
            break
        else:
            continue

假设我的输入是:9
和期望的输出是:["9","seven","bottles"]

1 个答案:

答案 0 :(得分:0)

是的,首先要提到的是Regex在这里不合适,因为你没有处理string但是使用list字符串,这使得它更容易。让我们来看看你的问题:

  

让我们说我的输入是:9,预期输出是:[" 9","七","瓶"]

您可以通过3行代码实现此目的:

for line in my_list: # iterate over your matrix
    if my_value in line: # if your list has your input
        return line # return that list

您可以重写您的功能,使其更容易,更短。我可能建议这样做:

def some_input(data):
    try:
        search = input("Search>>> ")
        if not search.isdigit():
            raise ValueError("Digits expected, instead {}".format(search))
    except ValueError:
        #handle your exception 
        pass

    # search for your list
    for line in data:
        if search in line:
            return line

要测试它,请致电print(some_input(my_list))。输入10后,我有下一个输出:

Search>>> 10
['10', 'ten', 'bottles']