简体   繁体   English

如何从Python列表中删除一个实例?

[英]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.

相关问题 我如何从我的列表中删除第 N 个元素,直到只剩下一个元素并在 python 中打印剩余的元素 - how do i remove the Nth element from my list until there's only one element remains and print that remaining element in python 如果我只有少数子列表元素,如何从列表中删除整个子列表? 蟒蛇 - How do I remove whole sub-list from list, if i have only few element of the sub-list? python 如何返回仅包含一个字符串元素的列表? 蟒蛇 - How do I return a list with only one stringed element? Python 如何从列表中删除一个字符串 - How do I remove one string from a list 如何删除列表中的第 n 个项目,直到 python 的列表中只剩下一个元素 - how do you remove the nth item in a list until only one element is left in the list in python 如何从python列表中删除转义符(\\)? - How do I remove escape character (\) from a list in python? 如何从 Python 中的给定字符串中删除子字符串列表? - How do I remove a list of substrings from a given string in Python? 如何从列表中删除相同的项目并在Python中对其进行排序? - How do I remove identical items from a list and sort it in Python? 如何从Python列表中删除字典索引? - How do I remove a dictionary index from a list on Python? 我如何从列表中删除一个项目并将其存储到 python 中的变量中 - How do i remove an item from a list and store it into a variable in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM