[Tutor] How can I replicate a list in a for loop
Raúl Cumplido
raulcumplido at gmail.com
Wed Feb 4 13:54:37 CET 2015
I think you want to use combinations_with_replacement:
>>> var = ['a', 'b', 'c', 'd', 'e']
>>> length=int(raw_input("enter the length of random letters you need "))
enter the length of random letters you need 2
>>> length
2
>>> from itertools import combinations_with_replacement
>>> [''.join(s) for s in combinations_with_replacement(var, 2)]
['aa',
'ab',
'ac',
'ad',
'ae',
'bb',
'bc',
'bd',
'be',
'cc',
'cd',
'ce',
'dd',
'de',
'ee']
On Wed, Feb 4, 2015 at 12:38 PM, Alan Gauld <alan.gauld at btinternet.com>
wrote:
> On 04/02/15 09:46, Suresh Kumar wrote:
>
> print var
>>>>>
>>>> ['a', 'b', 'c', 'd', 'e']
>>
>
> the user gave two so code should be like this
>>
>>> for i in itertools.product(var,var):
>>>>>
>>>> print i[0]+i[1]
>>
>
> output of code should be like this
>> aa
>> ab
>>
> ...
>
>> ee
>>
>
> based on the user given input of length i need to add var in for loop
>> if 3 given
>>
>>> for i in itertools.product(var,var,var):
>>>>>
>>>> print i[0]+i[1]+i[2]
>>
>
> OK, So the question is how to pass n copies of var to product()?
>
> You could do it by enclosing var in an outer list or tuple, then unpacking
> the result in the call to product():
>
> Untested...
>
> for i in itertools.product(*((var,) * n)):
> print ''.join(i)
>
> Does that work?
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list