【问题标题】:Comparing python tuples to find values also found in the previous and next tuples比较 python 元组以查找在前一个和下一个元组中也找到的值
【发布时间】:2012-03-22 12:28:54
【问题描述】:
a = [('08:57', 'Edinburgh', '12:08'), ('12:08', 'London', '12:50'), ('12:50', 'London', 14:44')]

所以我有时间列表(这些是公共汽车旅程),例如上面的“a”,每个元组都包含该段的开始和停止时间以及车站名称。然而,它们有时也包含只是“在公共汽车站等候”的腿。这些可以通过以下事实来识别:开始时间与前一段的停止时间相同,而停止时间与下一段的开始时间相同。我想识别这些然后删除它们。我想知道集合,但是公共汽车站的命名搞砸了,然后我想知道发电机。

那么粗略的:

gen = (item for item in a) #turn list into generator object

try:
    while 1:
        if gen.next()[2] == gen.next()[0] and gen.next()[0]:
            print 'match'
except StopIteration:            
    print 'all done'

确实有效,但它很糟糕,并且不允许我识别原始元组的索引位置来删除它。

非常希望有这样的方法。

【问题讨论】:

    标签: python list comparison tuples


    【解决方案1】:

    您可以遍历所有相邻腿的三元组并使用过滤掉不需要的腿

    filtered_a = [a[0]]
    for x, y, z in zip(a, a[1:], a[2:]):
        if x[2] != y[0] or y[2] != z[0]:
            filtered_a.append(y)
    filtered_a.append(a[-1])
    

    (此代码假定a 中至少有两条腿。)

    【讨论】:

    • zip 可以替换为任何rolling window iterator,如果您想避免复制列表。
    • @agf:你说得对,在这里链接迭代器解决方案肯定很有用,即使在这里使用它有点过分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多