Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unstring Python?

Tags:

python

I am a noob, How do I remove quotations and commas from my list? Or how do I "unstring"?

Without showing the dictionary (dic), the code I am using looks like this:

>>>import itertools
>>>list(itertools.product(dic[2], dic[3])

my results looks like this:

[('A', 'D'), ('A', 'E'), ('A', 'F'), ('B', 'D'), ('B', 'E'), ('B', 'F'), ('C', 'D'), ('C', 'E'), ('C', 'F')]

I would like them to look like this:

AD, AE, AF, BD, BE, BF,
like image 754
Moe Jan Avatar asked Dec 05 '25 19:12

Moe Jan


2 Answers

You want to produce a string, so you can use string manipulation (in particular, the join method):

>>> import itertools
>>> a = ['A', 'B']
>>> b = ['D', 'E', 'F']
>>> print ', '.join(''.join(x) for x in itertools.product(a, b))
AD, AE, AF, BD, BE, BF

Actually you don't even need itertools, you could just use a nested comprehension:

>>> print ', '.join(x + y for x in a for y in b)
like image 171
Niklas B. Avatar answered Dec 12 '25 10:12

Niklas B.


You can use join string method:

>>> import itertools
>>> p = list( itertools.product( ['a','b','c' ],['e','f','g'] ) )
>>> p
[('a', 'e'), ('a', 'f'), ('a', 'g'), ('b', 'e'), ('b', 'f'), ('b', 'g'), ('c', 'e'), ('c', 'f'), ('c', 'g')]
>>> ', '.join( a+b for (a,b) in p )
'ae, af, ag, be, bf, bg, ce, cf, cg'
like image 41
dani herrera Avatar answered Dec 12 '25 10:12

dani herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!