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


128

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

我需要进行编码,以便如果存在某个列表索引,然后运行一个函数。

我已经嵌套了if语句,这使情况变得更加复杂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.

1
看起来您想将强制类型转换n为整数而不是列表。我很困惑。
mVChr 2012年

2
是的,这里真正的问题是使用n的,而不是namsif小号
Wooble

在您的情况下,n不是列表。首先检查(铸造)为整数,然后可以根据要实现的效果进行迭代或枚举。
2012年

是的,输入错误。固定为nams []
2012年

“我有关于len(my_list)的sub if语句的事实。” 您是否考虑过len由于列表的至少是某个值的事实,隐含了哪些列表索引,这意味着什么?
Karl Knechtel'8

Answers:


157

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


6
是的 查看代码后,我的设置完全多余了。len(n)完成了我需要的一切。感谢您指出正确的方向。
user1569317'8

1
这不包括负索引。我知道的最好方法是try /除了IndexError,但是最好有一个简洁的方法来获取布尔值
艾布拉姆(Abram)

在Python中,列表上的负索引仅从列表末尾开始倒数。因此,它们不可能以影响列表长度的方式存在。
JonathanV

84

我需要进行编码,以便如果存在某个列表索引,然后运行一个函数。

这是try块的完美用法:

ar=[1,2,3]

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

# Note: this only is a valid test in this context 
# with absolute (ie, positive) index
# a relative index is only showing you that a value can be returned
# from that relative index from the end of the list...

但是,根据定义,Python列表中0和之间的所有项都len(the_list)-1存在(即,无需尝试,除非您知道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...

如果您正在寻找一些明确的“索引”思想,那么我想您是在问一个错误的问题。也许您应该考虑使用映射容器(例如dict)与序列容器(例如列表)。您可以这样重写代码:

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方法而不是try / except来获得较短的版本:

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

3
尝试阻止?我是Python的初学者,但是在编程中似乎很不行……流控制例外?我们不能控制的事情应该例外吗?
路易斯

3
@Luis我也是Python的初学者,但是从我在这些实例中读取的异常处理的内容来看,Python推广了C / Java / C#所没有的样式。见stackoverflow.com/questions/11360858/...
Tinister

句子“ Python列表中0到len(list)之间的所有索引”是绝对错误的。假设有一个列表x = [1、2、3],其中len_x =3。没有这样的索引3。该句子应该是:“ Python列表中所有索引都在0到len(list)-1之间” 。
Lior Magen

9
@LiorMagen:您说得对,我进行了编辑。对于这样一个学究的错误,投下相当受欢迎的帖子是很难的。一个简单的评论就足够了。
dawg

我要指出的是,将内容粘贴在a里面try不能告诉您索引是否存在,只是它可以获取-1-该索引实际上并不存在,但是会返回一个值。
乔治·莫尔

17

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


15

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

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

6

我需要进行编码,以便如果存在某个列表索引,然后运行一个函数。

您已经知道如何对此进行测试,并且实际上已经在代码中执行了这种测试

对于长的列表,有效索引n0通过n-1包容性。

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


是的,我有解决问题的工具,只是没有清楚地应用它们。感谢您指出正确的方向。
user1569317'8

为此,尤其是最后一句话,这是Python列表的重要属性,这使其与JavaScript数组和其他类似构造有所不同。
罗伯特

6

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

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

这还将测试负索引以及具有长度的大多数序列类型(如rangesstr)。

如果无论如何您以后都需要访问该索引处的项目,则宽恕要比权限容易,并且它也更快,更Python化。使用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

3

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

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

1

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

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

尽管这样会更简单:3 in range(len(your_list)
avloss '17

1
甚至这个3 in xrange(len(your_list)-也许不能做得比这更好
avloss

1

您可以尝试这样的事情

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];

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是更好的解决方案。


-3

不要在方括号前留任何空间。

例:

n = input ()
         ^

提示:您应该在代码上方和/或下方添加注释。不隐藏您的代码。


祝你今天愉快。


欢迎来到SO!您的回复看起来像是评论,而不是答案。拥有足够的声誉后,您就可以在任何帖子中发表评论。还要检查一下该怎么办。如果你打算回答,请阅读本怎样的应答遵循SO指引。
thewaywere是

-3

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

要检查字典dict是否存在索引“ id”:

dic = {}
dic['name'] = "joao"
dic['age']  = "39"

if 'age' in dic

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


1
这个问题的答案不好。问题是关于清单,而不是字典。在以下情况下,您的建议无法完成:[“ joao”,39]
Ruhrpottpatriot
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.