Python 3如何检查列表中的列表中是否已存在值 [英] Python 3 How to check if a value is already in a list in a list

查看:553
本文介绍了Python 3如何检查列表中的列表中是否已存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 3中有一个列表列表:

I have a list of lists in my Python 3:

mylist = [[a,x,x][b,x,x][c,x,x]]

(x只是一些数据)

我有代码可以做到这一点:

I have my code wich does that:

for sublist in mylist:
    if sublist[0] == a:
        sublist[1] = sublist[1]+1
        break

现在,我想添加一个条目,如果有任何子条目== a

now i want to add an entry, if there is any sublistentry ==a

我该怎么做?

推荐答案

使用 any() 测试子列表:

Use any() to test the sublists:

if any(a in subl for subl in mylist):

这会测试每个subl,但如果找到匹配项,则会尽早退出生成器表达式循环.

This tests each subl but exits the generator expression loop early if a match is found.

这不是不是,但是,返回匹配的特定子列表.您可以将 next() 与生成器表达式一起使用以查找第一个匹配项:

This does not, however, return the specific sublist that matched. You could use next() with a generator expression to find the first match:

matched = next((subl for subl in mylist if a in subl), None)
if matched is not None:
    matched[1] += 1

其中,None是默认值,如果生成器表达式引发StopIteration异常,则返回默认值,或者您可以忽略默认值,而使用异常处理:

where None is a default returned if the generator expression raises a StopIteration exception, or you can omit the default and use exception handling instead:

try:
    matched = next(subl for subl in mylist if a in subl)
    matched[1] += 1
except StopIteration:
    pass # no match found

这篇关于Python 3如何检查列表中的列表中是否已存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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