import itertools as iter
numbers = ['0', '1']
y = list(iter.product(numbers, repeat=2))
a = ''.join(y)
print(a)
When I try to convert y into a string, I join the string 'a' with y. But I keep getting the error "TypeError: sequence item 0: expected str instance, tuple found"
Any solutions?
CodePudding user response:
Your issue is that itertools.product
returns an iterator of tuples, so you have to join
each of the values in that list:
import itertools
numbers = ['0', '1']
y = itertools.product(numbers, repeat=2)
# output of product
# <iterator>(('0', '0'), ('0', '1'), ('1', '0'), ('1', '1'))
a = [''.join(t) for t in y]
a
# ['00', '01', '10', '11']
Note you don't need to convert y
to a list to use it in a comprehension.
CodePudding user response:
In your example, y
is a list of tuples, each of which contains two one-character strings.
If I'm understanding, I think what you want to do is this:
import itertools as it
numbers = ['0', '1']
y = list(it.product(numbers, repeat=2))
a = ''.join(''.join(x) for x in y)
print(a)
Output:
00011011
An alternative that produces the same result using the chain()
function in itertools is:
import itertools as it
numbers = ['0', '1']
y = list(it.product(numbers, repeat=2))
a = ''.join(it.chain(*y))
print(a)