基于每个列表元素中的字符值迭代列表(python)

时间:2017-01-29 13:30:50

标签: python list

我有以下形式的值列表:[0,1], [0,2], [1,3], [2,4], [3,5], [4,6], [5,7], [7,9]

我想遍历从[0,1]开始的列表,如果第二个字符(在本例中为1)等于另一个列表元素的第一个字符(在这种情况下,这将对应于[1,3],它会转到[1,3],然后转到[3,5], [5,7],最后转到[7,9]。此时它将从第二个元素([0,2])开始并执行相同的操作最终列在两个名单中。

为了澄清,列表本身包含偶数和奇数的值,这与我在此处显示的示例不同,因此我无法根据它进行拆分。

任何将我推向正确方向的想法都将非常感激。

2 个答案:

答案 0 :(得分:1)

这是一个递归解决方案,试图尽可能长时间地跟踪项目,同时处理备用的未访问路径:

from collections import defaultdict
def split(items):
    # create lookup
    lookup = defaultdict(set)
    for k, v in items:
        lookup[k].add(v)

    results = []
    while sum(map(len, lookup.values())):
        # get first element from remaining items
        first_k = min((k for k in lookup if len(lookup[k])))
        first = first_k, min(lookup[first_k])

        # follow that element
        results.append(follow(first, lookup))

    return results

def follow(item, lookup):
    item_k, item_v = item
    lookup[item_k].remove(item_v)

    result = [item]
    # loop through all follow-up items (if any)
    for next_item in sorted(lookup[item_v]):
        # recursively follow the follow-up item
        result.extend(follow((item_v, next_item), lookup))
    return result

使用lke this:

>>> def test(items):
        for x in split(items):
            print(x)

>>> test([[0,1], [0,2], [1,3], [2,4], [3,5], [4,6], [7,9]])
[(0, 1), (1, 3), (3, 5)]
[(0, 2), (2, 4), (4, 6)]
[(7, 9)]

它忽略了已经访问过的项目的路径:

>>> test([[0, 1], [1, 2], [4, 3], [2, 5], [5, 1]])
[(0, 1), (1, 2), (2, 5), (5, 1)]
[(4, 3)]

但是当有多个(排序,而不是原始顺序)时按顺序跟随所有这些:

>>> test([[0, 1], [1, 2], [1, 3], [2, 4], [3, 5]])
[(0, 1), (1, 2), (2, 4), (1, 3), (3, 5)]

它也适用于你的复杂例子:

>>> test([[0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [7, 9], [8, 10], [8, 11], [10, 12], [11, 13], [11, 14], [12, 15], [12, 16], [6, 8], [8, 17]])
[(0, 1), (1, 3), (3, 5), (5, 7), (7, 9)]
[(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12), (12, 15), (12, 16), (8, 11), (11, 13), (11, 14), (8, 17)]

答案 1 :(得分:0)

您无法通过使用" for"的常规方式进行迭代。循环,因为for循环不能跳转到特定值。所以使用" while"环。此代码查找与其last和first值匹配的所有值包。因此,您也可以使用它来查找复杂列表中间的匹配值。

listoflists = [[0,1], [0,2], [1,3], [2,4], [3,5], [4,6], [7,9]]

addr0 = 0
addr1 = 0
print len(listoflists)
while addr0 < len(listoflists):
    val0 = listoflists[addr0]
    last_num = val0[1]
    while addr1 < len(listoflists): # Second iteration for finding the matching value
        val1 = listoflists[addr1]
        if val1[0] == last_num:
            print "found: ",listoflists[addr0], listoflists[addr1] # Found the matching values
            addr0 = addr1
            break
        addr1 += 1
    addr0 += 1