将字符串列表与特殊规则组合在一起

时间:2017-04-13 16:19:47

标签: python

我是python的新手,我正在尝试修改现有的程序。我有几个列表,我需要以排序的方式对它们执行操作。例如,如果我有以下列表:

list_A = ['A1', 'A2', 'A3']
list_B = ['B1', 'B2', 'B3', 'B4', 'B5']

我希望得到一个带有elements = ['A1B1', 'A2B2', 'A3B3', 'B4B5']的新列表(即组合交替元素,直到较小的数组用完,然后组合大数组中的剩余元素。

这是2个列表的示例,但我尝试为N个列表执行此操作。

有没有' pythonic'实现这个目标的方式?

编辑:为N> 3案例添加更多信息(并使列表更大以更清楚地显示它们)。

list_A = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']
list_B = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6']
list_C = ['C1', 'C2', 'C3', 'C4']

从最小的'开始列出并开始配对。现在我处理的情况是有一个较短的列表,其他的长度相同。所以下面的A或B都可以。

预期输出:['C1B1', 'C2B2', 'C3B3', 'C4B4', 'B5B6', 'A1A2', 'A3A4', 'A5A6']

2 个答案:

答案 0 :(得分:0)

您的问题没有说明N>会发生什么? 3(或以上)情况,其中一个列表为空,但另外两个列表剩余(可能不相等)元素。

无论如何,我在实现这个递归解决方案时有一些乐趣,所以对于它的价值,这里就是。

list_A = ['A1', 'A2', 'A3']
list_B = ['B1', 'B2', 'B3', 'B4', 'B5']
list_C = ['C1', 'C2']

def combine(*lists):
    lists = filter(None, lists)
    if not lists:
        return []
    if len(lists) == 1:
        return [''.join(lists[0])]

    minlen = len(min(lists, key=len))
    head = [''.join(x) for x in zip(*lists)]
    tail = [l[minlen:] for l in lists]

    return head + combine(*tail)

a = combine(list_A, list_B)
b = combine(list_A, list_B, list_C)

print a # ['A1B1', 'A2B2', 'A3B3', 'B4B5']
print b # ['A1B1C1', 'A2B2C2', 'A3B3', 'B4B5']

它的工作原理如下:只要并非所有列表都用尽,算法将继续将剩余列表的元素压缩在一起。只有一个列表中只剩下一个项目,这些项目将连接成一个字符串并附加到结果中。这可能是也可能不是你想要的N> 2个案例。

答案 1 :(得分:-1)

# Notice:  the lists are composed of integers...
>>> a_list = [1, 2, 3]
>>> b_list = [4, 5, 6]
>>> c_list = [7, 8, 9]
>>> def cat(a_list):
...     string = ''
...     for i in a_list:
...             string += str(i)  # so we convert them to string.
...     return string
... 
>>> # Using a list comprehension and an un-named variable, along with the
>>> # zip() function.
>>> [cat(_) for _ in zip(a_list, b_list, c_list)]
['147', '258', '369']