[英]How do I remove only one instance from a list in Python?
So I have a Python script that reads in a .csv file of a play-by-play of a basketball game to calculate a plus/minus by lineup. 因此,我有一个Python脚本,该脚本读取篮球比赛的逐项比赛的.csv文件,以按阵容计算出加/减。 It keeps track of the current players on the floor in a list of the player's last names, and I encounter an error when a team has two players with the same last name (the play-by-play data doesn't use first names, only numbers and last names, and I don't keep track of their numbers).
它会在球员的姓氏列表中跟踪地板上的当前球员,并且当一个团队有两个具有相同姓氏的球员时,我会遇到一个错误(逐次比赛数据不使用名字,仅数字和姓氏,而我不跟踪其数字)。 The problem comes when I use lineup.remove(player) on one of the duplicate names, it removes both from the list.
当我在重复名称之一上使用lineup.remove(player)时,问题就来了,它从列表中同时删除了这两个名称。 Is there an easy way to only remove one, and if so, can I specify which?
有一种简单的方法可以只删除一个,如果可以,我可以指定哪个吗?
Example list would be 示例列表将是
['JONES', 'PATTERSON', 'SMITH', 'JONES', 'WILLIAMS']
From the docs: 从文档:
list.remove(x) Remove the first item from the list whose value is x. list.remove(x)从列表中删除值为x的第一项。 It is an error if there is no such item.
如果没有这样的项目,那就是错误的。
lineup = ['JONES', 'PATTERSON', 'SMITH', 'JONES', 'WILLIAMS']
lineup.remove('JONES') #should just remove the first occurrence of JONES
list = ['JONES', 'PATTERSON', 'SMITH', 'JONES', 'WILLIAMS']
cleared_list = dict((x, 1) for x in list).keys()
This list doesn't keep the order, however. 但是,此列表不保留顺序。
This one keeps the order but it's slightly more complex: 这个命令保持顺序,但稍微复杂一些:
list = ['JONES', 'PATTERSON', 'SMITH', 'JONES', 'WILLIAMS']
from itertools import count
seq = count()
d = {}
for x in list:
d.setdefault(x, seq.next())
l = d.items();
l.sort(lambda x, y: cmp(x[1], y[1]))
cleared_list = [x[0] for x in l]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.