[英]Python: Merge an item from one list to two items another
I am new to python, I am stuck, and I need help. 我是python的新手,被困住了,需要帮助。 Given a list as this: 给出如下列表:
listA = [1,2,3,4,5]
listB = [6,7,8,9,10,11,12,13,14,15]
I want to pick one Item from listA, Pick two Items from ListB, and have an output like this: 我想从listA中选择一个项目,从ListB中选择两个项目,并具有如下输出:
Item 1 from listA is joined with item 6 and 7 from listB
This should in a loop till there are no more items in listA 这应该一直循环,直到listA中没有更多项目为止
Thanks. 谢谢。 all help appreciated. 所有帮助表示赞赏。
Here is the solution 这是解决方案
listA = [1,2,3,4,5]
listB = [6,7,8,9,10,11,12,13,14,15]
j= 0
for i in listA:
print ("Item %d from listA is joined with item %d and %d from listB")%(i,listB[j],listB[j+1])
j+=2
you could try this: 您可以尝试以下方法:
listA = [1,2,3,4,5]
listB = [6,7,8,9,10,11,12,13,14,15]
for a, b1, b2 in zip(listA, listB[::2], listB[1::2]):
print(('Item {} from listA is joined with item {} and {} '
'from listB').format(a, b1, b2))
if you actually wanted to create a new list, merged in the way you described, this would work: 如果您确实想创建一个新列表,并按照您描述的方式进行合并,则可以这样做:
merged = [a for abc in zip(listA, listB[::2], listB[1::2]) for a in abc ]
print(merged) # [1, 6, 7, 2, 8, 9, 3, 10, 11, 4, 12, 13, 5, 14, 15]
taking the things apart: 拆开东西:
listB[::2] # [6, 8, 10, 12, 14] (every other element starting at 0)
listB[1::2] # [7, 9, 11, 13, 15] (every other element starting at 1)
[abc for abc in zip(listA, listB[::2], listB[1::2])] # [(1, 6, 7), (2, 8, 9), ...
and then you just need to flatten that list . 然后您只需要弄平那个列表 。
oh, you do not actually want to merge the list that way, but print out that string... that could be done like this: 哦,您实际上并不希望以这种方式合并列表,而是打印出该字符串...可以这样进行:
listA = [1,2,3,4,5]
listB = [6,7,8,9,10,11,12,13,14,15]
start,end,step = 0 , 2 , 2
for itemA in listA:
listB_item1,listB_item2 = listB[start:end]
print('Item',itemA,'from listA is joined with item',listB_item1,'and',listB_item2,'from listB')
start = start + step
end = start + step
RESULT 结果
Item 1 from listA is joined with item 6 and 7 from listB
Item 2 from listA is joined with item 8 and 9 from listB
Item 3 from listA is joined with item 10 and 11 from listB
Item 4 from listA is joined with item 12 and 13 from listB
Item 5 from listA is joined with item 14 and 15 from listB
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.