简体   繁体   中英

How to make duplicates of values in a list python

Quick question... searched and didn't find anything. I have this list:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

I want to have each value repeated 3 more times in the same list... How do I do so? I tried some for loops that .append to the list but things got messy. I ended up getting some list in list that were in lists. I have a feeling .append is not right for this scenario.

In [1]: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

In [2]: sorted(my_list * 3)

Note that you should not use list as a variable name, because it shadows the keyword list .

One other option is to use numpy :

In [8]: import numpy as np

In [9]: np.repeat(my_list, 3)

Use nested loops in a list comprehension.

>>> [x for x in L for y in range(4)]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

You can try something like this!

baselist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
[z for y in [[x]*4 for x in baselist] for z in y]

This is equivalent to:

listofLists = []
for x in baseList:
    listofLists.append([x]*4)

finalList = []
for y in listofLists:
    for z in y:
        finalList.append(z)

You see, the list comprehension simply shortens the logic, but whether it's more readable will depend on your grasp of comprehension syntax.

You could do like this,

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
>>> [j for i in lst for j in [i,i,i,i]]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

Another itertools variation using the flatten recipe

>>> m = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
>>> import itertools
>>> list(itertools.chain.from_iterable(itertools.izip(m,m,m,m)))
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> 

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