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的函数,它将接收2个列表并返回第三个列表,这些列表需要将第一个列表(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
我知道我在这个功能中没有正确使用索引。这个想法还可以吗?
答案 0 :(得分:3)
提示:使用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']
答案 1 :(得分:2)
zip
功能旨在将列表压缩在一起。你似乎想把第二个放在第一位,但你可以通过反转参数来做到这一点。
同时,这会给你一系列2元组,你必须扁平化。正确的方法是使用chain
。 (使用sum
不仅会产生误导,而且还会在二次方面变慢。)
最后,最终结果将是某种迭代(实际上是迭代器),而不是列表,因此您必须构造一个列表。所以:
def intercala_listas(a, b):
return list(itertools.chain.from_iterable(zip(b, a)))
答案 2 :(得分:1)
特别是使用sum()
来解决这个问题可能会让人感到困惑和缓慢(请参阅评论),这就是为什么避免它会更好的主意。方法如下:
[e for ts in zip(l2, l1) for e in ts]
答案 3 :(得分:1)
短而甜蜜:
list(sum(zip(l2, l1), ()))
答案 4 :(得分:1)
这是一个时髦的解决方案,使用带有偏移和步长的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
答案 5 :(得分:0)
您可以压缩列表,然后在理解中展平结果:
def intercala_listas(a, b):
c = list(zip(a, b))
return [elt for sublist in c for elt in sublist]
答案 6 :(得分:0)
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']
答案 7 :(得分: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 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']
由于本文中的大多数答案只能处理大小相等的列表,因此这是一种艺术方法,可以处理大小不同的列表