如果列表索引存在,请执行X.

时间:2012-08-02 21:36:21

标签: python python-2.7

在我的程序中,用户输入数字n,然后输入n个字符串数,这些字符串存储在列表中。

我需要编码,如果存在某个列表索引,则运行一个函数。

由于我已经嵌套了关于len(my_list)的语句。

,因此这变得更加复杂

这是我现在所拥有的简化版本,但不起作用:

n = input ("Define number of actors: ")

count = 0

nams = []

while count < n:
    count = count + 1
    print "Define name for actor ", count, ":"
    name = raw_input ()
    nams.append(name)

if nams[2]: #I am trying to say 'if nams[2] exists, do something depending on len(nams)
    if len(nams) > 3:
        do_something
    if len(nams) > 4
        do_something_else

if nams[3]: #etc.

13 个答案:

答案 0 :(得分:118)

使用列表len(n)的长度来通知您的决定而不是每个可能的长度检查n[i],这会更有用吗?

答案 1 :(得分:74)

我需要编码,如果存在某个列表索引,则运行一个函数。

这是try block的完美用法:

ar=[1,2,3]

try:
    t=ar[5]
except IndexError:
    print 'sorry, no 5'    

但是,根据定义,0len(the_list)-1之间的Python列表中的所有项都存在(即,除非您知道0 <= index < len(the_list),否则无需尝试)。

如果希望索引介于0和最后一个元素之间,则可以使用enumerate

names=['barney','fred','dino']

for i, name in enumerate(names):
    print i, name
    if i in (3,4):
        # do your thing with the index 'i' or value 'name' for each item...

如果你正在寻找一些定义的'索引'思想,我想你问的是错误的问题。也许您应该考虑使用mapping容器(例如dict)与sequence容器(例如列表)。您可以像这样重写代码:

def do_something(name):
    print 'some thing 1 done with',name

def do_something_else(name):
    print 'something 2 done with',name        

def default(name):
    print 'nothing done with',name     

something_to_do={  
    3: do_something,        
    4: do_something_else
    }        

n = input ("Define number of actors: ")
count = 0
names = []

for count in range(n):
    print "Define name for actor {}:".format(count+1),
    name = raw_input ()
    names.append(name)

for name in names:
    try:
        something_to_do[len(name)](name)
    except KeyError:
        default(name)

运行如下:

Define number of actors: 3
Define name for actor 1: bob
Define name for actor 2: tony
Define name for actor 3: alice
some thing 1 done with bob
something 2 done with tony
nothing done with alice

你也可以使用.get方法而不是试用/除了更短的版本:

>>> something_to_do.get(3, default)('bob')
some thing 1 done with bob
>>> something_to_do.get(22, default)('alice')
nothing done with alice

答案 2 :(得分:12)

len(nams)应该等于代码中的n。所有索引0 <= i < n“都存在”。

答案 3 :(得分:6)

只需使用以下代码即可完成

if index < len(my_list):
    print(index, 'exists in the list')
else:
    print(index, "doesn't exist in the list")

答案 4 :(得分:4)

  

我需要编码,如果存在某个列表索引,则运行一个函数。

您已经知道如何测试,实际上已经在您的代码中执行此类测试

长度为n的列表的有效索引为0n-1

因此,当且仅当列表的长度至少为i时,列表才有索引i + 1

答案 5 :(得分:4)

使用列表的长度是检查索引是否存在的最快解决方案:

def index_exists(ls, i):
    return (0 <= i < len(ls)) or (-len(ls) <= i < 0)

这也测试了负指数,以及大多数具有长度的序列类型(如rangesstr)。

如果你之后需要访问该索引处的项目,它是easier to ask forgiveness than permission,它也更快,更Pythonic。使用try: except:

try:
    item = ls[i]
    # Do something with item
except IndexError:
    # Do something without the item

这与以下相反:

if index_exists(ls, i):
    item = ls[i]
    # Do something with item
else:
    # Do something without the item

答案 6 :(得分:2)

如果要迭代插入的actor数据:

for i in range(n):
    if len(nams[i]) > 3:
        do_something
    if len(nams[i]) > 4:
        do_something_else

答案 7 :(得分:1)

Oneliner:

do_X() if len(your_list) > your_index else do_something_else()  

完整示例:

In [10]: def do_X(): 
    ...:     print(1) 
    ...:                                                                                                                                                                                                                                      

In [11]: def do_something_else(): 
    ...:     print(2) 
    ...:                                                                                                                                                                                                                                      

In [12]: your_index = 2                                                                                                                                                                                                                       

In [13]: your_list = [1,2,3]                                                                                                                                                                                                                  

In [14]: do_X() if len(your_list) > your_index else do_something_else()                                                                                                                                                                      
1

仅供参考。恕我直言,try ... except IndexError是更好的解决方案。

答案 8 :(得分:0)

好的,所以我认为这实际上是可能的(为了争论):

>>> your_list = [5,6,7]
>>> 2 in zip(*enumerate(your_list))[0]
True
>>> 3 in zip(*enumerate(your_list))[0]
False

答案 9 :(得分:0)

您可以尝试这样的事情

list = ["a", "b", "C", "d", "e", "f", "r"]

for i in range(0, len(list), 2):
    print list[i]
    if len(list) % 2 == 1 and  i == len(list)-1:
        break
    print list[i+1];

答案 10 :(得分:0)

很多答案,而不是简单的答案。

要检查数组Arr中是否存在索引“ id”:

if 'id' in Arr

如果存在“ id”,则返回true。

答案 11 :(得分:0)

这是我今天想解决这个问题的一种简单但计算效率低的方法:

只需在 my_list 中创建一个可用索引列表:

indices = [index for index, _val in enumerate(my_list)]

然后就可以在每个代码块之前进行测试了:

if 1 in indices:
    "do something"
if 2 in indices:
    "do something more"

但任何阅读本文的人都应该从以下位置获取正确答案:@user6039980

答案 12 :(得分:-3)

不要让括号前面有任何空格。

示例:

n = input ()
         ^

提示: 您应该在代码上和/或下添加注释。不在你的代码后面。

度过愉快的一天。