python - 是否有在字符串列表中搜索数字而不循环 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”。
解决方案
假设您希望避免嵌套循环并正在寻找 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']
推荐阅读
- javascript - 我可以减少这个护照代码吗?
- python - 从python模块多处理和kivy锁运行一个进程而没有答案
- ios - SF Pro Text Medium font is not found in swift code
- ios - 为不同的 Realm 对象交换和重新加载 tableView 中的数据
- r - Trouble with Spotfire R code (TERR) - Invalid subscript type 'list' error
- javascript - 如何将变量放在节点js中的双引号内
- google-cloud-endpoints-v2 - 使用带有自定义域的 Google 云端点框架 2.0
- r - 使用带有分类变量的 geom_rect 对 ggplot 图表的背景进行着色
- javascript - 具有两组数据的 c3 (v4) 散点图
- javascript - 鼠标悬停图片更大