[英]How do you merge two lists and return them as a tuple in a new list?
rules: If one list is shorter than the other, the last element of the shorter list should be repeated as often as necessary.规则:如果一个列表比另一个短,则应根据需要经常重复较短列表的最后一个元素。 If one or both lists are empty, the empty list should be returned.
如果一个或两个列表为空,则应返回空列表。
merge([0, 1, 2], [5, 6, 7])合并([0, 1, 2], [5, 6, 7])
should return [(0, 5), (1, 6), (2, 7)]应该返回 [(0, 5), (1, 6), (2, 7)]
merge([2, 1, 0], [5, 6])合并([2, 1, 0], [5, 6])
should return [(2, 5), (1, 6), (0, 6)]应该返回 [(2, 5), (1, 6), (0, 6)]
merge([ ], [2, 3])合并([ ], [2, 3])
should return []应该返回 []
this is what I've written so far这是我到目前为止所写的
def merge(a, b):
mergelist = []
for pair in zip(a, b):
for item in pair :
mergelist.append(item )
return mergelist
print(merge([0, 1, 2], [5, 6]))打印(合并([0、1、2]、[5、6]))
I'd use zip_longest
:我会使用
zip_longest
:
from itertools import zip_longest
def merge(a, b):
return list(a and b and zip_longest(a, b, fillvalue=min(a, b, key=len)[-1]))
Same thing, different style:同样的事情,不同的风格:
def merge(a, b):
if a and b:
short = min(a, b, key=len)
return list(zip_longest(a, b, fillvalue=short[-1]))
return []
Thanks for asking the question.感谢您提出问题。 I tried to amend your code as it is always easier to understand our own code.
我试图修改你的代码,因为它总是更容易理解我们自己的代码。 Please find modifications
请查找修改
def merge(a, b):
mergelist = []
if not a or not b:
return []
elif len(a) > len(b):
occ = len(a)-len(b)
b.extend([b[len(b)-1] for i in range(occ)])
elif len(a) < len(b):
occ = len(b)-len(a)
a.extend([a[len(a)-1] for i in range(occ)])
for pair in zip(a, b):
mergelist.append(pair)
return mergelist
print(merge(l,l1))
You need to manually append each tuple in the return list as you need to check if the length of the second list accordingly.您需要手动附加返回列表中的每个元组,因为您需要相应地检查第二个列表的长度。 This is one way of solving this
这是解决这个问题的一种方法
def merge(l1, l2):
new = []
for i in range(len(l1)):
if i > len(l2)-1:
s2 = l2[len(l2)-1] # use the last element of second list if there are no more elements
else:
s2 = l2[i]
new.append(l1[i], s2)
return new
"""
>>> merge([0,1,2],[5,6,7])
[(0, 5), (1, 6), (2, 7)]
>>> merge([2,1,0],[5,6])
[(2, 5), (1, 6), (0, 6)]
>>> merge([],[2,3])
[]
"""
from itertools import zip_longest
def merge(a,b):
if len(a) > len(b):
return list((zip_longest(a,b,fillvalue=b[-1])))
else:
return list((zip_longest(a,b,fillvalue=a[-1])))`
for example例如
a = [2,3,5]
b = [1,2]
merge(a,b)
[(2, 1), (3, 2), (5, 2)]
Link to documentation for zip_longest zip_longest 文档的链接
https://docs.python.org/3/library/itertools.html#itertools.zip_longest https://docs.python.org/3/library/itertools.html#itertools.zip_longest
This is actually somewhat tricky.这实际上有些棘手。 You would think something simple like this would work:
你会认为像这样简单的事情会起作用:
def merge(a, b):
# use iterator to keep iterations state after zip
a, b = iter(a), iter(b)
rtrn = list(zip(a, b))
try:
taila, tailb = rtrn[-1]
except IndexError: # one or both empty
return rtrn
# only one of these loops will run, draining the longer input list
rtrn.extend((ai, tailb) for ai in a)
rtrn.extend((taila, bi) for bi in b)
return rtrn
Here the trick is to use an iterator, not an iterable.这里的技巧是使用迭代器,而不是可迭代的。 An iterator keeps its state.
迭代器保持其状态。 So after the zip, both iterators should still point at the place where zip stopped.
所以在 zip 之后,两个迭代器仍然应该指向 zip 停止的地方。 However, this does not work if b is the shorter list.
但是,如果 b 是较短的列表,则这不起作用。 Because then zip will have removed one value from a and will discard it.
因为这样 zip 将从 a 中删除一个值并将其丢弃。 You have to be careful to avoid this.
你必须小心避免这种情况。 The easiest way is to just materialize two lists and deal with the length differences explicitely.
最简单的方法是将两个列表具体化并明确处理长度差异。
def merge(a, b):
# ensure that we have lists, not anything else like iterators, sets, etc
a, b = list(a), list(b)
rtrn = list(zip(a, b))
try:
taila, tailb = rtrn[-1]
except IndexError: # one or both empty
return rtrn
rtrnlen = len(rtrn)
# only one of these loops will run, draining the longer input list
# You could also use itertools.zip_longest for this
rtrn.extend((ai, tailb) for ai in a[rtrnlen:])
rtrn.extend((taila, bi) for bi in b[rtrnlen:])
return rtrn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.