繁体   English   中英

Python:将列表中项目的前 n 个字符与同一列表中所有其他项目的前 n 个字符进行比较

[英]Python: Compare first n characters of item in list to first n characters of all other items in same list

我需要将列表中项目的前 n 个字符与同一列表中其他项目的前 n 个字符进行比较,然后删除或保留其中一个项目。

在下面的示例列表中,“AB2222_100”和“AB2222_P100”将被视为重复项(即使它们在技术上是唯一的),因为前 6 个字符匹配。 比较这两个值时,如果 x[-4:] = "P100",则该值将保留在列表中,而没有“P”的值将被删除。 列表中的其他项目将被保留,因为没有重复项,无论字符串末尾是“P100”还是“100”后缀。 对于这种情况,永远不会有多个重复项(“P”或“P”)。

  • AB1111_100
  • AB2222_100
  • AB2222_P100
  • AB3333_P100
  • AB4444_100
  • AB5555_P100

我理解切片和比较,但一切都假设独特的价值。 我希望使用列表理解而不是长 for 循环,但也想了解我所看到的。 我已经迷失了试图找出这个非独特场景的集合、集合、zip 等。

切片和比较不会保留需要在最终列表中维护的所需后缀。

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)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM