python - 生成一个列表的列表,其元素来自另一个列表(Python)
问题描述
你如何生成一个列表列表,具有不同的大小,其元素来自另一个列表,比如说,a = [1,2,3]
?例如:如果我选择列表的长度为 2,那么我应该得到[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
.
解决方案
您要查找的内容称为“二项式组合”,您可以阅读此答案以了解更多信息,但此代码应与 2 的组合一起使用:
def algorithm(myList):
possible = [''.join(combination) for combination in product(myList, repeat= 2)]
return possible
print(algorithm(myList))
推荐阅读
- drupal - Drupal 7 模块升级到 Drupal 9
- docker - Openshift HTTP 在 60 秒后超时
- python - Request-html 每次调用函数时获取数据
- c++ - C++ 中带有模板的默认参数
- javascript - 使用 js-cookies,如何轻松将对象设置为 cookie?
- swiftui - 如何通过使用 @EnvironmentObject 来路由视图来导航到项目的详细视图?
- python - werkzeug.exceptions.BadRequestKeyError
- javascript - 如何编写一个接受任何输入的 Typescript hasOwnProperty 类型保护?
- xml - 在基于注释的方法中如何实现松散耦合
- javascript - 如何在不弄乱唯一 ID 的情况下克隆输入字段?