简体   繁体   中英

Append list every Nth index from another list

I have two lists:

gizmos = [('gizmo1', 314),
          ('gizmo1', 18),
          ('gizmo1', 72),
          ('gizmo1', 2),
          ('gizmo1', 252)]

owner =  ['owner1','owner3','owner32']

My goal result is to two combine both list into a new list, looping every other element:

newlist= [('owner1','gizmo1', 314),
          ('gizmo1', 18),
          ('owner3','gizmo1', 72),
          ('gizmo1', 2),
          ('owner32','gizmo1', 252)]

I attempted to zip the 3 lists but due to the lengths not matching this does not work.

You could do that with a list comprehension:

gizmos = [('gizmo1', 314), ('gizmo1', 18), ('gizmo1', 72), ('gizmo1', 2), ('gizmo1', 252)]

owner =  ['owner1','owner3','owner32']

newlist = [(owner[i//2], *giz ) if i%2==0 else giz for i, giz in enumerate(gizmos)]
print(newlist)
# [('owner1', 'gizmo1', 314), ('gizmo1', 18), ('owner3', 'gizmo1', 72), ('gizmo1', 2), ('owner32', 'gizmo1', 252)]

For odd indices, we just take the item from gizmos .

For even indices, we create a new tuple containing the owner, and the items of the original gizmo tuple which we unpack.

If it's ok to modify the list instead of creating a new one:

for i, o in enumerate(owner):
    gizmos[2*i] = o, *gizmos[2*i]

Or:

gizmos[::2] = ((o, *g) for o, g in zip(owner, gizmos[::2]))

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