python从单词列表生成所有组合

时间:2019-06-12 08:16:33

标签: python-2.7

我想创建一个简单的脚本来生成所有从用户名开始的可能的用户名。

示例输入:

craciun florin ionel

需要的输出:

craciun.florin
craciun.florin.ionel
craciun.ionel
florin.ionel
florin.craciun
ionel.florin.craciun
craciunflorin
ionel.craciun.florin
....

我尝试使用itertools工具,但是输出不能满足我的需要。

我当前的代码:

>>> import itertools
>>> names = ['craciun','florin','ionel']
>>> keywords = ['.'.join(i) for i in itertools.product(names, repeat=2) if i[0] != i[1]] 
>>> keywords
['craciun.florin', 'craciun.ionel', 'florin.craciun', 'florin.ionel', 'ionel.craciun', 'ionel.florin']

如何获得所需的输出?

2 个答案:

答案 0 :(得分:0)

执行此操作的一种可能方法是使用@IBAction func checkOut(_ sender: Any) { end = timeWheel.date let calendar = Calendar.current let startHour = calendar.component(.hour, from: start) let startDate = startHour < 12 ? calendar.date(byAdding: .minute, value: 30, to: start)! : start let difference = calendar.dateComponents([.hour, .minute], from: startDate, to: end) workLabel.text = "\(difference.hour!) timer og \(difference.minute!) minutter" } 两次,一次使用itertools.permutations(),另一次使用r=2,尽管这可能不是很有效且“ Pythonic”。 例如:

r=3

您可以遍历此结果列表进行格式化。

答案 1 :(得分:0)

一个班轮,因为我们爱他们:

keywords = [ ".".join(i) for i in itertools.chain.from_iterable(itertools.permutations(names, r) for r in [2, 3])]

结果:

['craciun.florin', 'craciun.ionel', 'florin.craciun', 'florin.ionel', 'ionel.craciun', 'ionel.florin', 'craciun.florin.ionel', 'craciun.ionel.florin', 'florin.craciun.ionel', 'florin.ionel.craciun', 'ionel.craciun.florin', 'ionel.florin.craciun']