简体   繁体   中英

How to replicate a list to a certain length?

I have list1 of a certain length and list2 of a certain length. Let's say:

list1 = [32, 345, 76, 54]

list2 = [43, 65, 76, 23, 12, 23, 44]

I need to make list1 loop back around until it is the same length as list2. Or, if list1 is longer, I need it to cut down to the length of list2. For the example above, I am looking to make:

list1 = [32, 345, 76, 54, 32, 345, 76]

It doesn't necessarily have to remain list1. It can be a new list I just need the same values from list1 looped back around a certain number of times. How do I go about doing this? I'm fairly new to python and I haven't been able to find anything that works.

Get to know the wonderful itertools module!

from itertools import cycle, islice

result = list(islice(cycle(list1), len(list2)))

If all you need is to iterate both list "together", this is even easier:

for x, y in zip(cycle(list1), list2):
    print(x, y)

Use itertools.cycle :

from itertools import cycle

new_list1 = [element for element, index in zip(cycle(list1), range(len(list2)))]
new_list1

Output:

[32, 345, 76, 54, 32, 345, 76]

You can do it with pure Python:

list1 = [32, 345, 76, 54]

list2 = [43, 65, 76, 23, 12, 23, 44]

l1, l2 = (len(list1) ,len(list2)) 
diff = (l2- l1) % l2
times = (l2 - l1) // l2
list1 = list1 * (times+1) + list1[:diff]
print(list1)

Result:

[32, 345, 76, 54, 32, 345, 76]

An alternative would be:

list1 = [32, 345, 76, 54]

list2 = [43, 65, 76, 23, 12, 23, 44]

times = len(list1) + (len(list2) - len(list1))
list1 = [list1[i%len(list1)] for i in range(times)]
print(list1)

Here is a more verbose solution using itertools.cycle which others have already demonstrated. It might be easier to understand this way.

target = len(list2) # the target length we want to hit
curr = 0 # keep track of the current length of output
out = [] # our output list
inf = cycle(list1) # an infinite generator that yields values

while curr < target:
    out.append(next(inf))
    curr += 1

print(out)
# [32, 345, 76, 54, 32, 345, 76]

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