简体   繁体   中英

Python 3.4.3 - How to save a itertools.permutations list usable?

i've tried many solutions to my problem, but I haven't find a solution yet.

import itertools

a = ['car','boat','plane']
b = list(itertools.permutations(a,))
print(b)

It gives this list when printed.

[('car', 'boat', 'plane'), ('car', 'plane', 'boat'), ('boat', 'car', 'plane'), ('boat', 'plane', 'car'), ('plane', 'car', 'boat'), ('plane', 'boat', 'car')]

But this isn't usable to me. I need something like that:

car boat plane
car plane boat
boat car plane
boat plane car
plane car boat
plane boat car

Space between words, no comma and 1 per line.

This was just a sample, because I have phrases with 20 words each and I need to make this with each one.

Now, just a real sample what I have to do.

import itertools
'phrase What are you doing to this cat?'
a = ['what','are','you','doing','to','this','cat?']
b = list(itertools.permutations(a,))
print(b)

The result will be a monster.

If you want to produce that actual string you have described you can do it with two join calls

'\n'.join(' '.join(r) for r in b)

The inner join concatenates the elements of each row with a ' ' separating them, the outer join then concatenates the rows with '\\n' between them. You can print the above directly or store it in a variable

You simply need to format it a bit. Join the items with a space, and separate them with a newline.

print(*(' '.join(item) for item in itertools.permutations(a,)), sep='\n')

Alternatively:

for item in itertools.permutations(a,):
    print(' '.join(item))

Just unpack the tuples returned by itertools.permutations(a,) and a for loop:

import itertools
a = 'what are you doing to this cat?'.split()
for permutation in itertools.permutations(a,):
    print(*permutation)

Using .split() on the phrase will make it easier to change out the sentence.

pprint.pprint is often useful for inspecting data. It doesn't give you precisely the form you want in this case, but it does give a useful form.

Code:

import itertools
from pprint import pprint

a = ['car','boat','plane']
b = list(itertools.permutations(a,))
pprint(b)

Result:

[('car', 'boat', 'plane'),
 ('car', 'plane', 'boat'),
 ('boat', 'car', 'plane'),
 ('boat', 'plane', 'car'),
 ('plane', 'car', 'boat'),
 ('plane', 'boat', 'car')]

You just need to do a string join with ',' for each element of each record from itertools.permutations, then join each record together with '\\n'. Here it is with a generator expression:

import itertools

a = ['car','boat','plane']
b = itertools.permutations(a)
s = '\n'.join((','.join(permutation) for permutation in b))
print(s)

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