【问题标题】:Iterate combinations of characters in multiple lists where the output string is in a specific order迭代多个列表中的字符组合,其中输出字符串按特定顺序排列
【发布时间】:2016-02-04 14:19:21
【问题描述】:

我正在尝试使用 itertools 创建一个 Python 脚本,其中:

我有 4 个列表,每个列表包含单个字符:

li1 = ["a", "b", "c"]
li2 = ["d", "e", "f"]
li3 = ["q", "w", "e"]
li4 = ["t", "y"]

我想按特定顺序输出以下所有可能的排列:

li1 + li2 + li3 + li1 + li4 + li1

其中li是列表中的字符串/字符,不能改变顺序/顺序

作为一个新手,我所能想到的就是将每个列表作为一个循环进行迭代,但我不知道如何同时执行 4 次

任何帮助将不胜感激

【问题讨论】:

  • 你的“列表”是集合..
  • 你读过documentation for itertools吗?它应该会有所帮助。
  • 您将li1 称为列表(实际设置)和列表中的项目。这是什么?

标签: python string list iteration concatenation


【解决方案1】:

您可以为此使用itertools.product()

import itertools

li1 = ["a","b","c"]
li2 = ["d","e","f"]
li3 = ["q","w","e"]
li4 = ["t", "y"]

for elem in itertools.product(li1, li2, li3, li1, li4, li1):
  print elem

(我冒昧地将您的集合更改为列表。但是,该代码也适用于集合,只是排列顺序会有所不同。)

【讨论】:

  • 谢谢!像魅力一样工作:)
猜你喜欢
  • 2018-07-14
  • 2013-05-14
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 2017-01-27
  • 1970-01-01
相关资源
最近更新 更多