Python-从不同文档中的列表中删除名称
我找到了更好的方法Python-从不同文档中的列表中删除名称,python,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
# -*- 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'
回溯(最近一次呼叫最后一次):
文件“C:\Users\hey\Desktop\Program\test.py”,第9行,在
列表。删除(x)
TypeError:描述符“remove”需要一个“list”对象,但收到一个“int”
两件事:
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
....
name.remove(x)
获取要删除的元素,而不是它的索引,因此可以使用name.remove(a)
或name.pop(x)
。请参阅列表。删除(x)应为名称。删除(x)谢谢!我仍然在寻找从文件permament中删除的名字,这样下次“Andrew”就不会出现在名单上了。再次感谢!仍在“在文件中删除它”。我需要打印随机选择。打印的和删除的名称必须相同
Andrew
Andrea
....