简体   繁体   中英

Is there a way to convert a list into a string?

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?

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.

If you want to make that into one string, you can then join again:

''.join(a)
# 00011011

or as one operation

a = ''.join(''.join(t) for t in y)

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)

I'm not sure what output you're looking for, put if you're going to use itertools I would keep the style functional:

import itertools 
from functools import reduce
numbers = ['0', '1'] 
y = itertools.product(numbers, repeat=2)
y = map(lambda x: ''.join(x), y)
y = reduce(lambda x, z: x + z, y)
print(y)

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