2012-06-15 55 views
0

我有以下阵列(在python):指数误差

arr= ['\n', ' a#B\n', ' c#D\n'] 

现在我一想拆就“#”对此我写如下代码:

for i in arr: 
g=i.split("#")[1] 

我收到以下错误:

g=i.split("#")[1] 
IndexError: list index out of range 

我没有得到为什么我收到错误。有人可以善意地帮助纠正它。

+0

顺便说一句,它被称为'list',而不是python中的“数组”。 –

+0

是否要保留尾部'\ n' – Levon

回答

2

当您的列表的第一个元素'\n'被分配给i时,它不包含"#",所以结果列表只有一个元素长而不是两个。尝试检索索引1失败,但会出现索引0

1

错误是由于第一次拆分导致只包含1个元素['\n']的列表导致的,因此[1]的索引值超出了界限。

请参见:

for i in arr: 
    g = i.split("#") 
    print g 

输出:

['\n'] 
[' a', 'B\n'] 
[' c', 'D\n'] 

一个快速的方法来解决这将是:

[i.split('#')[1] for i in arr if len(i.split('#')) > 1] 

尽管它包含两个调用split()

下面的一个有点冗长,但只调用split()一次。

for i in arr: 
    g = i.split('#') 
    if len(g) > 1: 
     g = g[1] 

由于@kindall在下面的意见建议,使用partition()split()这里也替代。

+0

更好的方法是使用'partition()'而不是'split()'。它总是返回三个元素,你可以得到最后一个;如果分隔符不存在,它将是空白的。 – kindall

+0

@kindall分区而不是split()? – Levon

+0

是的,澄清说。 – kindall

0

数组中,你可以通过遍历的第一个元素没有哈希#所以当你调用它的分裂,它在列表中['\n']所以当您尝试通过[1]它可以访问的第二个项目只返回1项没有发现它给你的错误。

记住,在Python索引从0开始,而不是1

2

其他人解释为什么你得到例外。这里有一个可能对你有用的不同方法的想法。

与Python 2.5开始,字符串对象长出了新partition方法:

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

>>> arr= ['\n', ' a#B\n', ' c#D\n'] 
>>> for s in arr: 
...  print s.partition('#') 
... 
('\n', '', '') 
(' a', '#', 'B\n') 
(' c', '#', 'D\n') 

可以拉开字符串没有遇到分离器是否被发现或不是错误时抛出。