为什么itertools.permutations()返回的是列表而不是字符串?

35 投票
4 回答
73717 浏览
提问于 2025-04-17 06:14

为什么itertools.permutations()会返回每个排列的字符或数字列表,而不是直接返回一个字符串呢?

举个例子:

>>> print([x for x in itertools.permutations('1234')])
>>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ]

那它为什么不直接返回这个呢?

>>> ['1234', '1243', '1324' ... ]

4 个回答

3

排列可以用于字符串和列表,下面是一个例子。

x = [1,2,3]

如果你想对上面的列表进行排列

print(list(itertools.permutations(x, 2)))

# the above code will give the below..
# [(1,2),(1,3),(2,1)(2,3),(3,1),(3,2)]
16

因为它需要一个可迭代的对象作为参数,但它不知道这个参数是一个字符串。这个参数在文档中有说明。

http://docs.python.org/library/itertools.html#itertools.permutations

54

itertools.permutations() 的工作原理很简单。它接受一个可以遍历的对象作为参数,然后总是返回一个迭代器,这个迭代器会生成元组。它不会(也不应该)特别处理字符串。如果你想得到字符串的列表,你可以自己把元组连接起来:

list(map("".join, itertools.permutations('1234')))

撰写回答