简体   繁体   English

在 Python 的二维列表中搜索元素

[英]Searching elements in a 2D list in Python

I have a two-dimensional list that has about 1000 elements.我有一个包含大约 1000 个元素的二维列表。 It looks something like this:它看起来像这样:

myList = [['1', 'John', 'Doe', 'jdoe@email.com', '234-35-2355'], ['2', 'Rebecca', 'Swan', 'rswan@email.com', '244-56-4566'], ['3', 'Terry', 'Smith' 'tsmith@email.com', '345-45-1234']]

Index [1] is their first name, and I want to search this list (that has 1000 people, only used 3 for simplicity), to see if they are in the list, and if they are, print their information, without using Numpy.索引 [1] 是他们的名字,我想搜索这个列表(有 1000 人,为简单起见只使用了 3 个),看看他们是否在列表中,如果有,打印他们的信息,而不使用 Numpy .

So far I have:到目前为止,我有:


firstName = input('Enter the first name of the record: ')

row = len(myList)

found = False
for row in my list:
    for element in row:
        if element == firstName:
            found = True
            break

    if found:
        break

if found:
    print('User ID: ', myList[0])
    print('First Name: ', myList[1])
    print('Last Name: ', myList[2])
    print('Email: ', myList[3])
    print('Login IP: ', myList[4])

else:
    print('There is no record found with first name', firstName)

Now this seems to be working to find if the person is there or not, however I am having trouble with printing the information after, because I do not know how to find the index of the person, I believe if I had the index the print would be something like myList[index][1]现在这似乎正在寻找这个人是否在那里,但是我在打印信息之后遇到了麻烦,因为我不知道如何找到这个人的索引,我相信如果我有索引打印类似于myList[index][1]

EDIT: Okay I see that it was a simple fix of changing myList[1] to row[1].编辑:好的,我看到这是将 myList[1] 更改为 row[1] 的简单修复。 Now say you search a name and two people in the list have the same name and you want to print both sets of information, how would I go about that?现在假设您搜索一个名字并且列表中的两个人具有相同的名字,并且您想打印两组信息,我将如何 go 呢?

One of many possible ways:许多可能的方法之一:

def findByName(name, lst):
    return filter(lambda x: x[1] == name, lst)

for item in findByName("John", myList):
    print(item)

This yields这产生

['1', 'John', 'Doe', 'jdoe@email.com', '234-35-2355']


Or directly with a listcomp: 或直接使用 listcomp:

 persons = [entry for entry in myList if entry[1] == name]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM