我發現了一個更好的方法。Python - 從不同文檔中的列表中刪除名稱
# -*- coding: cp1252 -*-
import random
# Import a file with the names in class
name = [i.strip().split() for i in open("input.txt").readlines()]
# Draw a name
a =(random.choice(name))
# Print the name
print a
# Find the index from the list
x = name.index(a)
# Delete the name from the list
list.remove(x)
的input.txt的是:
Andrew
Andrea
....
不過這裏有什麼錯誤?
運行當我得到這個錯誤: [ '安德魯']
Traceback (most recent call last):
File "C:\Users\hey\Desktop\Program\test.py", line 9, in <module>
list.remove(x)
TypeError: descriptor 'remove' requires a 'list' object but received a 'int'
'name.remove(X)'接受要被刪除的元素,不是指數,所以要麼使用'name.remove(一)'或'name.pop(X)' 。請參閱[列表中的一些文檔](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) – Dettorer 2014-11-24 13:22:51
list.remove(x)應該是name.remove(x) – Pengman 2014-11-24 13:22:52