我想在python中合并两个列表,列表具有不同的长度,因此较短列表的元素在最终列表中的间隔尽可能相等.即我想采取[1, 2, 3, 4]并['a','b']合并它们以获得类似的列表[1, 'a', 2, 3, 'b', 4].它需要能够与那些不准确的倍数太名单功能,所以它可以采取[1, 2, 3, 4, 5]与['a', 'b', 'c']生产[1, 'a', 2, 'b', 3, 'c', 4, 5]或相似.它需要保留两个列表的顺序.
我可以通过一个冗长的蛮力方法看到如何做到这一点但是因为Python似乎有很多优秀的工具可以做各种我不知道的聪明的事情(还)我想知道是否还有其他的东西优雅我可以使用?
注意:我使用的是Python 3.3.
如果是输入
round_robin(range(5), "hello")
Run Code Online (Sandbox Code Playgroud)
我需要o/p as
[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']
Run Code Online (Sandbox Code Playgroud)
我试过了
def round_robin(*seqs):
list1=[]
length=len(seqs)
list1= cycle(iter(items).__name__ for items in seqs)
while length:
try:
for x in list1:
yield x
except StopIteration:
length -= 1
pass
Run Code Online (Sandbox Code Playgroud)
但它给出了错误
AttributeError: 'listiterator' object has no attribute '__name__'
Run Code Online (Sandbox Code Playgroud)
如何修改代码以获得所需的o/p
我是Python的新手,我仍然很难将语言本身用于我的程序.这是我到目前为止所拥有的:
# Purpose: 'twolists' = takes 2 lists, & returns a new list containing
# alternating elements of lists.
# Return = final_list
# Parameter = list1, list2
def twolists(list1, list2): # don't forget to return final_list
alt_list = []
a1 = len(list1)
a2 = len(list2)
for i in range(# ? ):
# append one thing from list1 to alt_list - How?
# append one thing from list2 to alt_list - How?
Run Code Online (Sandbox Code Playgroud)
现在该程序应该产生如下输出:
outcome = twolists([ ], ['w', 'x', 'y', …Run Code Online (Sandbox Code Playgroud) 是否有可能为循环2列表与另一个大小最小的"重新循环"?
例:
list = [1,2,3,4,5,6,7,8,10]
list2 = [a,b]
newlist = []
for number, letter in zip(list, list2):
newlist.append(item)
newlist.append(item2)
Run Code Online (Sandbox Code Playgroud)
循环停在[1a,2b]因为list2中没有其他项目,list2是否可以重新开始直到list1为空?即:newlist = [1a,2b,3a,4b,5a,6b]等?
thkx!
我想把两个编号"编织"在一起.
例:
x = [1,2,3]
y = [4,5,6]
result = [1,4,2,5,3,6]
Run Code Online (Sandbox Code Playgroud)
这是我的功能,我无法找出它为什么不起作用:
def weave(list1,list2):
lijst = []
i = 0
for i <= len(list1):
lijst += [list1[i]]
lijst += [list2[i]]
i + 1
Run Code Online (Sandbox Code Playgroud)