+ 15
How to duplicate set of items in list into list? (Python3)
Say my list is this: l=[1,2,3,4,5,6] Say I want to duplicate every set of three numbers so my result is this: l=[1,2,3,1,2,3,4,5,6,4,5,6] It has to duplicate right after the set of numbers. I can't think of a good way to do this through a for loop, although I might just be tired. I need this for expanding an images y values, if you were curious why I need this.
9 Respuestas
+ 17
A very crude, but effective version. I'll be reducing it to an error-resistant one-liner tomorrow. But for the time being - there you go :)
https://code.sololearn.com/cZlLfe9tWoP2/?ref=app
+ 18
Thank you Kuba! You always Luba when I need it the most!
+ 11
@Kirk Schafer
The best challenges are real problems! I actually needed this and you guys saved me alot of trouble. So thank you all!!!
+ 10
Adding this because "me" trying to do this with Pythonic features was almost disastrously convoluted...so at this point it's just funny to me (3 ways):
https://code.sololearn.com/cL1DOm8zF6rS/?ref=app
+ 7
@Kirk I spent some time still yesterday but all I got was a lousy map object or a 2D list :D
+ 7
yeah, the iterators gave me fits... (@Kuba) I started with starmap and even an iterator of iterators, (imap? izip?) which was undefined on SoloLearn & I can't find now.
Noticing things like accumulate() today and @richard's chain() it's clear I need to learn more.
Thanks @Ahri for the challenge.
+ 6
Ah...I was looking for something like count() yesterday. Here's an Ahri-while-compatible, less terrible version (only because I need to clarify iterators for myself + maybe it helps to note):
l=[1,2,3,4,5,6,7,8,9]
from itertools import count
out=[]
ctr=count(0,3)
while True:
c=next(ctr) # ctr.next() should work; doesn't.
out += l[c:c+3] * 2
if c>=len(l): break
print(out)
+ 6
That is Sololearn's idea how I get it - learn playing, play learning ;)
P.S. Now I understand why Guido wanted to dispose of all those lambdas, map and reduce :D
+ 5
# there is also the itertools option with a comprehension
from itertools import chain
def test(Alist,size):
return list(chain(*(Alist[x:x+size]*2 for x in range(0,len(Alist),size))))
print(test([1,2,3,4,5,6,7,8,9],3))
print(test([1,2,3,4,5,6,7,8,9,10],2))