2014-11-24 68 views
-2

我发现了一个更好的方法。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' 
+1

'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

+1

list.remove(x)应该是name.remove(x) – Pengman 2014-11-24 13:22:52

回答

1

两件事情:

  1. 你不需要索引。删除需要一个元素而不是索引。
  2. 用名称替换列表。

代码:

import random 
name = [i.strip().split() for i in open("input.txt").readlines()] 
a =(random.choice(name)) 
print a 
name.remove(a) 

在文件中删除:

import random 
name = open("input.txt", 'r').readlines() 
name.remove(random.choice(name)) 
with open("input.txt", 'w') as f: 
    for row in name: 
     f.write(row) 

注意我input.txt中可能会比你的人。矿是由endlines分离。该算法适用于:

Andrew 
Andrea 
.... 
+0

谢谢!不过,我正在寻找从文件permament中删除的名称,所以“安德鲁”不会在下一次列表上 – Sinder33 2014-11-24 13:33:19

+0

再次谢谢!仍然在“在文件中删除它”。我需要打印random.choice。打印和删除的名称必须相同 – Sinder33 2014-11-24 13:54:46