Python:为什么我不能从列表中弹出一个值?

时间:2016-02-16 02:02:50

标签: python list python-3.x

我不确定这里到底发生了什么。我试图尽可能具体。有人能告诉我为什么这不起作用吗?我得到一个超出范围的" pop索引"当我尝试从a_list弹出一个项时出错,循环显示在a_list中。我在大学课程中学习这个。谢谢!我真的希望这不是一个愚蠢的问题。输出如下。

[38, 38, 25, 25, 7, 60, 5, 35, 97]
compare append 5
compare append 7
compare append 25
pop a_list 25
[5, 7, 25, 25, 35, 38, 38, 60, 97]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-141-a73ef6b20848> in <module>()
      4     a.append(random.randint(0,100))
      5 print (a)
----> 6 k_largest(a,3)

<ipython-input-137-a9f599ea78c6> in k_largest(a_list, k)
     12                 print("pop a_list " + str(item))
     13                 print(a_list)
---> 14                 a_list.pop(item)
     15         else:
     16             if item not in compare_list:

IndexError: pop index out of range

输出:

#import <Glimpse/Glimpse.h>

@implementation myViewController
- (void)viewDidAppear
{
        [super viewDidAppear:animated];

        // Create a new Glimpse object.
        Glimpse *glimpse = [[Glimpse alloc] init];

        // Start recording and tell Glimpse what to do when you are finished
        [glimpse startRecordingView:self.view onCompletion:^(NSURL *fileOuputURL) {
            NSLog(@"DONE WITH OUTPUT: %@", fileOuputURL.absoluteString);
        }];

        // Create a subview for this example
        UIView *view = [[UIView alloc] initWithFrame:CGRectInset(self.view.bounds, 40.0f 40.0f)];
        view.backgroundColor = [UIColor greenColor];
        view.alpha = 0.0f;

        [self.view addSubview:view];

        // We are going to record the view fading in.
        [UIView animateWithDuration:5.0 animations:^{
            view.alpha = 1.0f;
        } completion:^(BOOL finished) {
            // Since our animation is complete, lets tell Glimpse to stop recording.
            [glimpse stop];
        }];
 }
@end

2 个答案:

答案 0 :(得分:2)

list.pop()会删除元素的索引,而不是要删除的项目。请尝试使用list.remove()

答案 1 :(得分:0)

正如Python文档所说:

  

array.pop([I])

     

从数组中删除索引为i的项并返回它。该   可选参数默认为-1,因此默认情况下最后一项是   删除并返回。

您需要提及索引号以使用array.pop()。