简体   繁体   English

如何删除python列表中的每个项目之一

[英]How to delete one of each item in a python list

I have a list that looks like this: 我有一个看起来像这样的列表:

lst = ['p','p','p','p','p','m','m','m','n','n','n','n','d','d']

I want to remove one of each item. 我要删除每个项目之一。 Currently my code looks like this: 目前,我的代码如下所示:

for item in lst: 
    if (lst[-1] == lst[-2]) == True: 
        del(lst[-2])

That is if the last two items of the list are the same the second from the last should be deleted, but my code does not work. 就是说,如果列表中的最后两项相同,则应该删除第二项,但是我的代码不起作用。

You can make a set of the unique characters, loop over a copy of your list, and then remove items from the set while adding to an output list: 您可以制作一set独特的字符,遍历列表的副本 ,然后在添加到输出列表中的同时从集合中删除项目:

lst = ['p','p','p','p','p','m','m','m','n','n','n','n','d','d']

chars_to_remove = set(lst)
counter = len(chars_to_remove)
output = []

for item in lst[:]:
    if item in chars_to_remove:
        chars_to_remove.remove(item)
        continue
    else:
        output.append(item)

print(output)

Result: 结果:

['p', 'p', 'p', 'p', 'm', 'm', 'n', 'n', 'n', 'd']

Note : You still need to define what happens when there is only a single instance of a string in your list. 注意 :您仍然需要定义当列表中只有一个字符串实例时会发生什么。 (ie Does it get deleted as well?) In the above code, it will be deleted. (即是否也将其删除?)在上面的代码中,它将被删除。 But that can be changed like so, by adding another condition to the loop body: 但这可以通过在循环体中添加另一个条件来改变:

Sample input : lst = ['p','p','p','p','p','m','m','m','q','n','n','n','n','d','d'] 输入示例: lst = ['p','p','p','p','p','m','m','m','q','n','n','n','n','d','d']

for item in lst[:]: if lst[:].count(item) == 1: output.append(item) continue elif item in chars_to_remove: chars_to_remove.remove(item) continue else: output.append(item)

Result: ['p', 'p', 'p', 'p', 'm', 'm', 'q', 'n', 'n', 'n', 'd'] 结果: ['p', 'p', 'p', 'p', 'm', 'm', 'q', 'n', 'n', 'n', 'd']

You can also, use sum and groupby : 您也可以使用sumgroupby

from itertools import groupby

lst = ['p', 'p', 'p', 'p', 'p', 'm', 'm', 'm', 'n', 'n', 'n', 'n', 'd', 'd']
final = sum((list(g)[:-1] for _, g in groupby(lst)), [])
print(final)

Output: 输出:

['p', 'p', 'p', 'p', 'm', 'm', 'n', 'n', 'n', 'd']

Assuming you want to remove single occurrences in the list, can be done in one line: 假设要删除列表中的单个匹配项,可以一行完成:

[lst.remove(c) for c in set(lst)]

This does not return the answer, but modifies your list in place, so lst is now trimmed. 这不会返回答案,而是会修改您的列表,因此现在修剪了lst

Or wrapped into a potentially more useful function: 或包装成一个可能更有用的功能:

def remove_first_occurence(lst):
    l = lst.copy()
    [l.remove(c) for c in set(l)]
    return l

You could give this a shot 你可以试一下

result = []

for _, u in groupby(lst):
    new_u      = list(u)
    last_index = max(1, len(new_u) - 1)

    result += new_u[:last_index]

It is not clear what your expected result it. 目前尚不清楚您的预期结果。 Your code will not work because you are iterating a list while mutating it. 您的代码将无法工作,因为您正在对列表进行变异时对其进行迭代。 Instead, iterate over a copy ( lst[:] ). 而是遍历一个副本( lst[:] )。

for item in lst[:]: 
    if (lst[-1] == lst[-2]): 
        del(lst[-2])

lst
# ['p', 'p', 'p', 'p', 'p', 'm', 'm', 'm', 'n', 'n', 'n', 'n', 'd']

However, you code still needs more to resolve: 但是,您的代码仍然需要更多解决:

I want to remove one of each item 我要删除每个项目之一

Try this instead: 尝试以下方法:

import itertools as it


lst = ['p','p','p','p','p','m','m','m','n','n','n','n','d','d']
list(it.chain.from_iterable((list(g)[:-1] for _, g in it.groupby(lst))))
# ['p', 'p', 'p', 'p', 'm', 'm', 'n', 'n', 'n', 'd']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将列表中的每个项目添加到Python中的上一个项目? - How to add each item in a list to the previous one in Python? 尝试使用循环打印列表中的每个项目,然后删除项目 Python - Trying to use a loop to print each item in the list and then delete item Python 如何将Python列表的每一项巧妙地传递给函数并更新列表(或创建一个新列表) - How to neatly pass each item of a Python list to a function and update the list (or create a new one) 如何使用.count计算一个列表中每个项目出现在python中另一个列表中的次数? - How to use .count to calculate number of times each item in one list appears in another list in python? 依次打印列表中的每个项目(PYTHON) - Print each item in list one second after the other (PYTHON) 如何在Python中将列表中的每个项目附加到列表中的列表? - How to append each item from a list to a list in a list in Python? 如何分隔每个列表项以减去该项目 python - How do I seperate each list item to minus that item, python 如何获取另一个列表中的列表项以在Python 3中的第一个列表中将其删除 - How to get a list item that is in another list to delete it on the first in Python 3 如何使用列表中每个项目中的数字对列表进行排序? Python - How to sort a list using digits in each item of the list? Python Python:如何为列表中的每个项目打印带有标签的列表 - Python: How to print a list with labels for each item within the list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM