我找到了更好的方法。
# -*- 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'
答案 0 :(得分:1)
两件事:
代码:
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可能不是你的。我的终点是分开的。该算法适用于:
Andrew
Andrea
....