简体   繁体   English

检查元素是否存在于列表中

[英]check if the element is present in list or not

I have a list hi 我有一个清单嗨

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']


if '4KUI' in w:
    print "got !!"

But, I am not able to print 'got'. 但是,我无法打印'got'。 how can I do that? 我怎样才能做到这一点?

This is because there is no element in w that is '4KUI' . 这是因为w中没有元素为'4KUI' There certainly is one that starts that way, though. 当然,肯定有一个这样的开始。
I think this is what you're looking for: 我认为这是您要寻找的:

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']
if any(i.startswith("4KUI") for i in w):
    print "got !!"

you are comparing the whole string there. 您正在比较整个字符串。 you need to do something like 你需要做类似的事情

for string in w:
    if '4kui' in string:
        print "got!!"

Example

#!/usr/bin/python

entries = ['Glasgow', 'Edinburgh', 'Scotland', 'Dundee']

if [entry for entry in entries if entry.startswith('Dun')]:
        print "Found entry for Dundee"

Execution 执行

python example.py python example.py

In this context "in" is determining whether '4KUI' is the value of one of the elements in your list. 在这种情况下,“ in”确定“ 4KUI”是否为列表中元素之一的值。 What you want is to see if '4KUI' is contained within one of the elements in your list. 您要查看的是列表中的元素之一是否包含“ 4KUI”。 Try this: 尝试这个:

w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']

for f in w:
  if '4KUI' in f:
    print "got !!"
w = ['4KUI_YLR242C.pdb', '2CQA_CGI-52.pdb', '4G4S_YFR051C.pdb']

for item in w:
        if "4KUI" in item:
                print "got !!"

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

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