.clear()列表不起作用 - python

时间:2016-10-09 14:17:16

标签: python list runtime-error

我正在编写一些应该找到数字素数分解的代码。主函数通过数字递增;我这样做是因为我想使用代码进行计时实验。我不介意它不是超级高效,对我来说,项目的一部分将使我自己更有效率。它还没有完全完成(例如,它不简化素数分解)。我已经测试了除main函数之外的所有函数,并且它们已经工作,因此这些函数没有问题。

我的代码是

import math 
import time

primfac=[]

def primes(n):
    sieve = [True] * n
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
    return [2] + [i for i in xrange(3,n,2) if sieve[i]]


def factfind(lsp,n): #finds factors of n among primes
    for i in lsp:
        if n%i==0:
            primfac.append(i)
        else:
            i+=1

def primfacfind(n1,n2):
    while n1 < n2:
        n = n1

        time_start = time.clock()

        factfind(primes(n),n)
        print primfac

        time_elapsed = time.clock() - time_start
        print "time:", time_elapsed

        primfac.clear()

        n1+=1

print primfacfind(6,15)

运行它会产生输出

[2, 3]
time: 7.5e-05
Traceback (most recent call last):
  File "python", line 43, in <module>
  File "python", line 39, in primfacfind
AttributeError: 'list' object has no attribute 'clear'

我不确定出了什么问题。它给出了素数分解的正确数字,它正在打印时间,但它似乎无法清除列表。评论primfac.clear()行有效。

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:8)

在Python 3.3中添加了del primfac[:]方法。可以通过public class DiceRoll1 extends JFrame implements ActionListener { private JTextField txtNotation; private JButton btRoll, btShuffle; private List<Integer> dealtCard; private History history; public DiceRoll1() { initComponents(); dealtCard = new ArrayList<>(); history = new History(); } public void initComponents() { //designing the userform setSize(400, 500); setLayout(new FlowLayout()); setTitle("Dice Roll"); txtNotation = new JTextField("2d6"); btRoll = new JButton("Roll"); btShuffle = new JButton("Shuffle"); txtNotation.setColumns(20); getContentPane().add(txtNotation); getContentPane().add(btRoll); getContentPane().add(btShuffle); btRoll.addActionListener(this); btShuffle.addActionListener(this); } /** * @param args the command line arguments */ public static void main(String[] args) { new DiceRoll().setVisible(true); } @Override public void actionPerformed(ActionEvent e) { JButton source = (JButton) e.getSource(); if (source.equals(btRoll)) { } else if (source.equals(btShuffle)) { } } public void displayOutput(String message) { System.out.println(message); } } 在早期版本中实现等效。

答案 1 :(得分:2)

Python的list在Python 3.x之前没有clear方法。您的代码将无法在Python 2.x或更早版本中运行。您可以创建新列表或删除旧列表的所有内容。

#create a new list 
primfac = []

#or delete all the contents of the old list
del primfac [:]