按给定索引在列表列表中搜索 [英] Search in lists of lists by given index

查看:28
本文介绍了按给定索引在列表列表中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两项列表的列表,需要在其中搜索内容.

I have a list of two-item lists and need to search for things in it.

如果列表是:

list = [['a','b'], ['a','c'], ['b','d']]

我可以很容易地搜索一对

I can search for a pair easily by doing

['a','b'] in list

现在,有没有办法查看我是否有一对字符串仅出现在第二个位置?我可以这样做:

Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:

for i in range (0, len(list)):
    if list[i][1]==search:
       found=1

但是没有 for 循环有没有(更好的)方法?我不需要知道 i 或在找到后继续循环.

But is there a (better) way without the for loop? I don't need to know i or keep the loop going after it's found.

推荐答案

你总是会有一个循环——有人可能会想出一个巧妙的单行代码,在调用 map() 或类似的,但它总是会在那里.

You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to map() or similar, but it's always going to be there.

除非性能是主要因素,否则我总是倾向于使用干净简单的代码.

My preference would always be to have clean and simple code, unless performance is a major factor.

这可能是您代码的 Pythonic 版本:

Here's perhaps a more Pythonic version of your code:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
    if sublist[1] == search:
        print "Found it!", sublist
        break
# Prints: Found it! ['a', 'c']

一旦找到匹配项,它就会跳出循环.

It breaks out of the loop as soon as it finds a match.

(顺便说一下,您在 ['b''d'] 中有一个错字.)

(You have a typo, by the way, in ['b''d'].)

这篇关于按给定索引在列表列表中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆