有没有更好的方法来构建这样的列表?

时间:2010-12-15 04:55:36

标签: python list zip

我是Python的新手,我喜欢它,但想知道是否有更好的方法来做一些列表操作。

这个是相对理智的,但似乎我可能错过了内置函数。

def zip_plus(source_list, additional_list):
    """
    Like zip but does plus operation where zip makes a tuple

    >>> a = []
    >>> zip_plus(a, [[1, 2], [3, 4]])
    >>> a
    [[1, 2], [3, 4]]
    >>> zip_plus(a, [[11, 12], [13, 14]])
    >>> a
    [[1, 2, 11, 12], [3, 4, 13, 14]]
    """
    if source_list:
        for i, v in enumerate(additional_list):
            source_list[i] += v
    else:
        source_list.extend(additional_list)

这个是hacky,难以阅读,任何关于做它更清洁或更pythonic的想法?

def zip_join2(source_list, additional_list):
    """
    Pretty gross and specialized function to combine 2 types of lists of things,
    specifically a list of tuples of something, list
    of which the something is left untouched

    >>> a = []
    >>> zip_join2(a, [(5, [1, 2]), (6, [3, 4])])
    >>> a
    [(5, [1, 2]), (6, [3, 4])]
    >>> zip_join2(a, [(5, [11, 12]), (6, [13, 14])])
    >>> a
    [(5, [1, 2, 11, 12]), (6, [3, 4, 13, 14])]
    """
    if source_list:
        for i, v in enumerate(additional_list):
            source_list[i] = (source_list[i][0], source_list[i][1] + v[1])
    else:
        source_list.extend(additional_list)

4 个答案:

答案 0 :(得分:4)

def zip_plus(first, second):
    return [x+y for (x,y) in zip(first, second)]

def zip_join2(first, second):
    return [(x[0], x[1]+y[1]) for (x,y) in zip(first, second)]

答案 1 :(得分:3)

首先,为了更加Pythonic,我会避免改变输入。

其次,您可能需要更像dict的内容,而不是zip_join2函数的元组列表。像这样:

>>> a = {5 : [1,2], 6 : [3,4]}
>>> b = {5 : [11,12], 6 : [13,14]}
>>> for k,v in b.iteritems():
...     a[k].extend(v)
>>> a = {5: [1,2,11,12], 6: [3,4,13,14]}

您可能还想考虑使用defaultdict(来自集合模块),以防第二个字典的第一个字典中没有密钥。

答案 2 :(得分:1)

def zip_plus(source_list, additional_list):
  return map(lambda a, b: a + b if a and b else a or b, source_list, additional_list)

def zip_join2(source_list, additional_list):
  return map(lambda x, y: (x[0], x[1] + y[1]), source_list, additional_list)

map并行运作。

答案 3 :(得分:1)

使用元组解包和布尔逻辑列出理解。

<强> zip_plus:

from itertools import izip_longest
def zip_plus(first, second):
    return [(a or []) + (b or []) for a, b in izip_longest(first, second)]

print zip_plus([], [[1, 2], [3, 4]])
print zip_plus([[1, 2], [3, 4]], [[11, 12], [13, 14]])
print zip_plus([[1, 2], [3, 4]], [[11, 12]])
print zip_plus([[1, 2]], [[11, 12], [13, 14]])

<强> zip_join2:

from itertools import izip_longest
def zip_join2(first, second):
    return [(a or c or 0, (b or []) + (d or [])) for (a, b), (c, d) in \
              izip_longest(first, second, fillvalue=(None, None))]

print zip_join2([], [(5, [1, 2]), (6, [3, 4])])
print zip_join2([(5, [1, 2]), (6, [3, 4])], [(5, [11, 12]), (6, [13, 14])])

0表示a为0且c为None的情况。 其中一些让我也感到畏缩。