python - Python:将列表中项目的前n个字符与同一列表中所有其他项目的前n个字符进行比较
问题描述
我需要将列表中项目的前 n 个字符与同一列表中其他项目的前 n 个字符进行比较,然后删除或保留其中一个项目。
在下面的示例列表中,“AB2222_100”和“AB2222_P100”将被视为重复(即使它们在技术上是唯一的),因为前 6 个字符匹配。比较两个值时,如果 x[-4:] = "P100",则该值将保留在列表中,而没有“P”的值将被删除。列表中的其他项目将被保留,因为没有重复项,无论字符串末尾是“P100”还是“100”后缀。对于这种情况,永远不会有多个重复项(“P”或没有)。
- AB1111_100
- AB2222_100
- AB2222_P100
- AB3333_P100
- AB4444_100
- AB5555_P100
我了解切片和比较,但一切都假设有独特的价值。我希望使用列表理解而不是长 for 循环,但也想了解我所看到的。我迷失了试图找出这个非独特场景的集合、集合、拉链等。
切片和比较不会保留最终列表中需要维护的所需后缀。
newList = [x[:6] for x in myList]
这就是它应该如何开始和结束。
myList = ['ABC1111_P100', 'ABC2222_100', 'ABC2222_P100', 'ABC3333_P100', 'ABC4444_100', 'ABC5555_P100']
newList = ['ABC1111_P100', 'ABC2222_P100', 'ABC3333_P100', 'ABC4444_100', 'ABC5555_P100']
解决方案
如您的评论中所述,您不能在一个班轮中执行此操作。您可以及时执行此操作,O(n)
但会占用一些额外空间:
myList = ['ABC1111_P100', 'ABC2222_100', 'ABC2222_P100', 'ABC3333_P100', 'ABC4444_100', 'ABC5555_P100']
seen = dict()
print(myList)
for x in myList:
# grab the start and end of the string
start, end = x.split('_')
if start in seen: # If we have seen this value before
if seen[start] != 'P100': # Did that ending have a P value?
seen[start] = end # If not swap out the P value
else:
# If we have not seen this before then add it to our dict.
seen[start] = end
final_list = ["{}_{}".format(key, value) for key, value in seen.items()]
print(final_list)
推荐阅读
- python - Python:如何在不读取数据帧两次的情况下将数据帧从 .py 文件调用到另一个 py 文件?
- javascript - JavaScript - 加入数据视图
- discord - 其他不和谐机器人状态
- python - 解决python和numpy/scipy中的两步插值
- php - PHP逐步通过大数组进行迭代
- python - 使用 Table.read_table 比使用 pd.read_csv 有优势吗?
- java - ElasticSearch 突然死机,无法响应
- node.js - 如何在浏览器中查看我的固定 IP 的 Express 应用程序
- c++ - 使用远程工具链时,CLion 导航到错误的定义路径
- python - 如何在 python 中使用 SKLearn 对多项逻辑回归进行假设检验?