【问题标题】:Keyword combiner tool关键词组合工具
【发布时间】:2021-02-07 00:21:29
【问题描述】:

我想挑战自己,我想构建一个像这样的关键字组合工具:

我想使用 Python 构建它,但我真的不知道如何将列表中的项目与另一个列表组合:

a = ['blue', 'red', 'green']
b = ['shoes', 'shirt', 'pants']

c = a + b

如果我打印 c 我会得到:

['blue', 'red', 'green', 'shoes', 'shirt', 'pants']

但我希望它可以这样组合:

 - blue shoes
 - red shoes 
 - green shoes

【问题讨论】:

标签: python


【解决方案1】:

如果你想得到一个包含所有可能组合的列表,这可能是最快的方法

c = [(x+" "+y) for x in a for y in b]

它遍历两个列表并将所有组合写入新列表中。

最后:c = ['blue shoes', 'blue shirt', 'blue pants', 'red shoes', 'red shirt', 'red pants', 'green shoes', 'green shirt', 'green pants']

【讨论】:

  • 我没有投反对票(这是正确的......),但这基本上是 product 所做的......
  • 我明白,但最好不要只为这件事导入自定义模块,否则可以在一行中完成......
  • itertools 是一个内置库...同样,我没有投反对票,您的回答非常正确...
猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多