如果列表索引存在,则执行 X [英] If list index exists, do X
本文介绍了如果列表索引存在,则执行 X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的程序中,用户输入数字n
,然后输入n
个字符串,这些字符串存储在一个列表中.
In my program, user inputs number n
, and then inputs n
number of strings, which get stored in a list.
我需要编写这样的代码,如果某个列表索引存在,则运行一个函数.
I need to code such that if a certain list index exists, then run a function.
由于我嵌套了关于 len(my_list)
的 if 语句,这变得更加复杂.
This is made more complicated by the fact that I have nested if statements about len(my_list)
.
这是我现在所拥有的简化版本,但不起作用:
Here's a simplified version of what I have now, which isn't working:
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.
推荐答案
使用列表的长度 len(n)
比检查 len(n)
的长度更有用吗?code>n[i] 每个可能的长度?
Could it be more useful for you to use the length of the list len(n)
to inform your decision rather than checking n[i]
for each possible length?
这篇关于如果列表索引存在,则执行 X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文