0
def intercala_listas(lista1, lista2):

    l1 = ["b", "d", "f", "h"]
    l2 = ["a", "c", "e", "g"]
    assert intercala_listas(l1,l2) == ['a', 'b', 'c', 'd', 'e','f', 'g', 'h']
    assert l1 == ["b", "d", "f", "h"]
    assert l2 == ["a", "c", "e", "g"]

我必须创建一个名为 intercala_lista 的函数,它将接收两个列表并返回第三个列表,该列表需要将第一个列表 (l1) 的元素放在奇数索引中,将第二个列表 (l2) 的元素放在偶数索引中,就像显示的断言一样。

我不期待一个完整的答案,但我需要知道如何做到这一点。


我试过这样的事情:

def intercala_listas(lista1, lista2):
    lista = [8]
    for i in range(len(lista)):
        if lista[i].index%2 == 0:
            lista[i] = lista1[i]
        else:
            lista[i] = lista2[i]
        return lista

我知道我在这个函数中没有正确使用索引。这个想法好吗?

4

8 回答 8

4

提示:使用zip函数:

>>> zip(l2, l1)
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

关于您的回答:Python 列表不是数组。它们没有固定的大小,所以只需将元素附加到末尾:

def intercala_listas(lista1,lista2):
    # Assumes lista1 and lista2 are the same length 
    lista = []

    for i in range(len(lista1)):
        lista.append(lista1[i])
        lista.append(lista2[i])

    return lista

>>> print intercala_listas(list("aceg"), list("bdfh"))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
于 2013-10-17T19:28:58.367 回答
2

这是一个使用带有偏移量和步长的 Python 切片分配的时髦解决方案,以展示 Python 的一些鲜为人知的功能 - 嵌套列表理解或其他解决方案zip通常可能更可取。此解决方案假定两个列表具有相同的长度:

def intersect_lists(l1, l2):
    result = [0] * len(l1) * 2 #create result list of required size
    result[::2] = l2 #assign l2 to the slice of every second item in result
    result[1::2] = l1 #as above but starting at offset 1
    return result
于 2013-10-17T19:36:23.223 回答
2

zip功能旨在将列表压缩在一起。你似乎想把第二个放在第一位,但你可以通过颠倒参数来做到这一点。

同时,这为您提供了必须展平的 2 元组序列。正确的方法是使用chain. (使用sum不仅会产生误导,而且速度也很慢。)

最后,最终结果将是某种可迭代的(实际上是迭代器),而不是列表,因此您必须从中构造一个列表。所以:

def intercala_listas(a, b):
    return list(itertools.chain.from_iterable(zip(b, a)))
于 2013-10-17T19:40:28.383 回答
2
import itertools

list(itertools.chain(*zip(l2, l1)))
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

或者

list(itertools.chain.from_iterable(zip(l2, l1)))
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
于 2016-12-05T00:06:23.713 回答
1

简短而甜蜜:

list(sum(zip(l2, l1), ()))
于 2013-10-17T19:35:52.173 回答
1

特别是使用sum()这个问题可能会令人困惑和缓慢(见评论),这就是为什么最好避免它。就是这样:

[e for ts in zip(l2, l1) for e in ts]
于 2013-10-17T19:30:36.207 回答
0

您可以压缩列表,然后在理解中展平结果:

def intercala_listas(a, b):
    c = list(zip(a, b))
    return [elt for sublist in c for elt in sublist]
于 2013-10-17T19:34:54.200 回答
0
def intercalate_2lists(l1, l2, s1=0, s2=1, app=nan, incr=1, if_print= False):
    """
    Usage:  Intercalate two lists: L1 and L2 into a new list L3
    
        S1 and S2 are indices in L3 where interacalation of L1 or L2 will start.
        INCR is the number of empty elements APP added to L3 at each iteration,
        such iteration can be empty if current L3 index is inferior to min(S1, S2).
        Intercalation in L3 starts at min(S1,S2) and the first element of the corresponding list is used.
        Intercalation of the list corresponding to max(S1, S2) starts once the iteration through L3 reach the index max(S1, S2)
        if S1>0 and S2>0: L3 is appended with APP. until iteration of L3 reach min(S1, S2)
        if S1 == S2: S2 is incremented by 1 (user should avoid this situation)
        S1, S2 can be used to swap the order of integration of L1 and L2, i.e. id S2<S1: L2 will be used first
    Parameters:
    L1,L2   (list)(list) lists to intercalate
    S1,S2   (int),(int) indices in L3 to start to intercalate L1 and L2
    INCR    (int) step of increment of L3 (spacing between L1&L2 elements)
    APP     (var) element to put in empty cells of L3
    IF_PRINT (bool) Track assembly of L3. Use only for short L3 lists otherwise be ready to saturate your screen with printed output
    
    Return:
    L3 list
    """
    
    len_l1 = len(l1)
    len_l2 = len(l2)
    result = list()
    t1,t2 = False, False
    d1,d2 = False, False
    f1,f2 = True, True
    if s1 == s2: s2 += 1 # SAFEGUARD
    if incr == 0: incr=1 # SAFEGUARD
    c, c1, c2 = 0, 0 ,0
    while c1 < len_l1 or c2 < len_l2:
        for x in range(incr):
            result.append(app)
        if all([c >= s1, f1]): t1 = True; d1 = True; f1 = False; d2=False
        elif all([c >= s2, f2]): t2 = True; d2 = True; f2 = False; d1=False
        if if_print: print("beg:" + str(c) + '\t' + str(c1) + '\t' + str(c2), d1, d2)
        if t1:
            if d1:
                result[-1] = l1[c1]
                c1 += 1
                if t2:
                    if c2 < len_l2: d1 = False; d2 = True
                    if if_print: print("end:" + str(c) + '\t' + str(c1) + '\t' + str(c2), d1, d2)
                    if c1 == len_l1: t1 = False
                    c += incr
                    if if_print: print(result,'___')
                    continue
        if t2:
            if d2:
                result[-1] = l2[c2]
                c2 += 1
                if t1:
                    if c1 < len_l1: d1=True; d2 = False
        if if_print: print("end:" + str(c) + '\t' + str(c1) + '\t' + str(c2), d1, d2)
        if c1 >= len_l1: t1 = False
        if c2 >= len_l2: t2 = False
        c += incr
        if if_print: print(result)
    return result

intercalate_2lists() 的应用:

a = ["A", "B", "C", "D", "E", "F", "G"]
b = [1, 2, 3, 4]
# Use the default behavior
print("case1:", intercalate_2lists(a[:4], b))
print("case2:", intercalate_2lists(a, b))
print("case3:", intercalate_2lists(b, a))
# Use advanced modes
print("case4:", intercalate_2lists(a, b, s1=4, s2=2))
print("case5:", intercalate_2lists(b, a, s1=3, s2=10, incr=3, if_print=0))
print("case6:", intercalate_2lists(a[:4], b, s1=2, incr=1, if_print=0))

上述调用的结果:

case1:['A', 1, 'B', 2, 'C', 3, 'D', 4]
case2:['A', 1, 'B', 2, 'C', 3, 'D', 4, 'E', 'F', 'G']
case3:[1, 'A', 2, 'B', 3, 'C', 4, 'D', 'E', 'F', 'G']
case4:[nan, nan, 1, 2, 'A', 3, 'B', 4, 'C', 'D', 'E', 'F', 'G']
case5:[nan, nan, nan, nan, nan, 1, nan, nan, 2, nan, nan, 3, nan, nan, 'A', nan, nan, 4, nan, nan, 'B', nan, nan, 'C', nan, nan, 'D', nan, nan, 'E', nan, nan, 'F', nan, nan, 'G']
case6:[nan, 1, 'A', 2, 'B', 3, 'C', 4, 'D']

由于这篇文章中的大多数答案只处理大小相等的列表,因此这是一种能够处理不同大小列表的艺术方法。

于 2019-12-06T15:38:53.800 回答