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”
两件事:

  • 您不需要索引。remove接受元素而不是索引
  • 将列表替换为名称
  • 代码:

    要在文件中删除它,请执行以下操作:

    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
    ....