简体   繁体   中英

Python: Merge an item from one list to two items another

I am new to python, I am stuck, and I need help. 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM