首页 > 解决方案 > 是否有在字符串列表中搜索数字而不循环 2 次的功能?

问题描述

想象一下列表中的一些纸牌游戏,如下所示:

list1 = ['1 of Spades', '1 of Diamonds', '2 of Hearts']

我正在尝试类似的事情,但没有成功:

popped = [s for s in list1 if s[:1] in list1.count(s[:1]) > 1]

如何获得所有相同价值的卡并将其删除而不循环 2 次?在此示例中,应弹出“黑桃 1”和“方块 1”。

标签: pythonlistloops

解决方案


假设您希望避免嵌套循环并正在寻找 O(n) 解决方案,您可以使用 Counter 字典来确定每个卡值的数量,然后根据它过滤列表:

list1 = ['1 of Spades', '1 of Diamonds', '2 of Hearts']

from collections import Counter

counts = Counter( c.split(" ",1)[0] for c in list1 )
list1  = [ c for c in list1 if counts[c.split(" ",1)[0]] == 1 ]

输出:

print(list1) 

# ['2 of Hearts']

推荐阅读