python - ITEM 在 python FOR 循环中是变量
问题描述
我正在尝试找出一种更有效的方法来用 python 编写以下内容。实际上,我想自动创建一个列表,其中包含另一个列表的所有可能组合。
因此,对于下面的示例,将创建 aaa、aab、aac ..... ccc
我想要做的是使组合列表的大小更大,即上升到 a、b、c 和 d。这目前涉及在下面添加另一个 FOR 语句,以便能够运行第 4 个组合。
无论如何,是否可以根据组合列表中的项目数使 FOR 语句的项目列表也可变(类似于我如何使表达式列表变量)?
(我已经查看了使用可变数量的 for 循环创建元组,但如果我们尝试做同样的事情则无法解决,我的其他搜索只找到有关如何制作可迭代变量的问题)
word_ls=['A','B','C']
num_word =[]
loop_len =len(word_ls)
#create the expression which will be used to generate the word listing, which will then be used to match up to the log/ lat co-ordinates
expression=''
for create_string in range(loop_len): # this replaces > num_word.append(word_ls[item1] + '.' + word_ls[item2] + '.' + word_ls[item3])
expression = expression + "word_ls[item{0}".format(create_string+1)+ "] + '.' + "
expression = expression.strip(" + '.' +")
for item1 in range(loop_len):
for item2 in range(loop_len):
for item3 in range(loop_len):
num_word.append(eval(expression))
解决方案
我相信您正在寻找https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement
例如
import itertools
items = ['A', 'B', 'C', 'D']
list(itertools.combinations_with_replacement(items, len(items)))
或者可能是上面@andrepd 建议的产品。
list(itertools.product(items, repeat=len(items)))
这取决于您是想要输出中的 CBA 之类的东西,还是只想要严格排序的 ABC。
推荐阅读
- javascript - Display current time from timer
- java - 无法在多文档事务中创建命名空间(MongoDB 4.0、Spring Data 2.1.0、Spring Boot)
- c# - 游戏对象在游戏视图中不可见
- xamarin.forms - Xamarin 表单:如何在应用程序关闭时从推送通知中保存数据
- rust - How do I create a proc_macro_attribute?
- html - 替换 HTML 字符串
- ocaml - 优拓不响应
- c - 无法在 mergeSort 函数中释放内存
- javascript - SAP UI5:合并/连接两个表
- python - 为什么使用 BeautifulSoup find_all 方法会导致错误(列表索引超出范围)?