2014-11-24 47 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