代码之家  ›  专栏  ›  技术社区  ›  user469652

python,格式化这个列表

  •  1
  • user469652  · 技术社区  · 14 年前

    我有一个清单 [(1,2),(1,8),(2,3),(2,7),(2,8),(2,9),(3,1),(3,2),(3,5),(3,6),(3,7),(3,7),(3,9)]

    我想让它看起来像 [('1'、''2'、'8')、('2'、''3'、'7'、'8'、'9')、('3'、''、'2'、'5'、'6'、'7'、'7'、'9')]

    如何编写此循环的代码?真的试过几次了,结果什么也没发生。请帮助~~

    4 回复  |  直到 14 年前
        1
  •  0
  •   stew    14 年前
    a = [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6),  (3, 7), (3, 7), (3, 9)]
    
    x1=None  # here we keep track of the last x we saw
    ys=None  # here we keep track of all ys we've seen for this x1
    
    result = [] 
    
    for x,y in a:
        if x != x1:  # this is an x we haven't seen before
            if ys:   # do we have results for the last x?
                result.append( ys ) 
            ys = [ x, '', y ] # initialize the next set of results
            x1 = x
        else:
            ys.append( y ) # add this to the results we are buliding
    
    if ys:
        result.append( ys )  # add the last set of results
    
    print result
    
        2
  •  2
  •   S.Lott    14 年前

    步骤1。将列表转换为词典。每个元素都是具有公共键的值列表。(提示:键是每对的第一个值)

    步骤2。现在将每个字典格式化为键、空格和值列表。

        3
  •  2
  •   mechanical_meat nazca    14 年前

    不完全是你要求的,但也许更容易合作?

    >>> from itertools import groupby
    >>> L = [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
    >>> for key, group in groupby(L, lambda x: x[0]):
    ...     print key, list(group)
    ... 
    1 [(1, 2), (1, 8)]
    2 [(2, 3), (2, 7), (2, 8), (2, 9)]
    3 [(3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
    

    Link to documentation .

    编辑:
    我想这更像是你想要的:

    >>> d = {}
    >>> for key, group in groupby(L, lambda x: x[0]):
    ...     d[key] = [i[1] for i in group]
    ... 
    >>> d
    {1: [2, 8], 2: [3, 7, 8, 9], 3: [1, 2, 5, 6, 7, 7, 9]}
    

    如果您绝对希望密钥是一个字符串,您可以这样编码:

    d[str(key)] = [i[1] for i in group]
    
        4
  •  2
  •   Mark Tolonen    14 年前
    from collections import defaultdict
    
    s = [
        (1,2),(1,8),
        (2,3),(2,7),(2,8),(2,9),
        (3,1),(3,2),(3,5),(3,6),(3,7),(3,7),(3,9)
        ]
    
    D = defaultdict(list)
    for a,b in s:
        D[a].append(b)
    
    L = []
    for k in sorted(D.keys()):
        e = [str(k),'']
        e.extend(map(str,D[k]))
        L.append(tuple(e))
    
    print L
    

    输出:

    [('1', '', '2', '8'), ('2', '', '3', '7', '8', '9'), ('3', '', '1', '2', '5', '6', '7', '7', '9')]
    

    你必须向你的老师解释它是如何工作的;^)