python-3.x - 通过重复获得不同的数字集
问题描述
我有一个数字列表:
lst = [1, 2, 3, 1,4]
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only
# one permuatation is possible
if len(lst) == 1:
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range(len(lst)):
m = lst[i]
# Extract lst[i] or m from the list. remLst is
# remaining list
remLst = lst[:i] + lst[i + 1:]
# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l
if __name__ == "__main__":
lst = [1, 2, 3, 1,4]
v_out = permutation(lst)
print(v_out)
我只得到 4 个长度的排列,我想要所有长度的排列,并且只有不同的排列。但在每个排列中,重复是允许的。
解决方案
这应该可以工作...使用permutations
itertools 中的功能并set
排除所有内容以防止将重复项添加到整体结果中
In [20]: from itertools import permutations
In [21]: a = [1, 1, 2, 3]
In [22]: all_results = set()
In [23]: for i in range(1, len(a)):
...: all_results.update(set(permutations(a, i)))
...:
In [24]: all_results
Out[24]:
{(1,),
(1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 2),
(1, 2, 1),
(1, 2, 3),
(1, 3),
(1, 3, 1),
(1, 3, 2),
(2,),
(2, 1),
(2, 1, 1),
(2, 1, 3),
(2, 3),
(2, 3, 1),
(3,),
(3, 1),
(3, 1, 1),
(3, 1, 2),
(3, 2),
(3, 2, 1)}
In [25]:
推荐阅读
- matlab - matlab 通过 tcp/ip 调用 matlab
- c# - 无法从程序集“Microsoft.EntityFrameworkCore.Relational”加载类型“RelationalReferenceCollectionBuilderExtensions”
- ruby-on-rails - 自定义 Rails 初始化程序作为一个类
- awk - 如何在 gsub 中读取参数
- php - 如何使用 PHP 从 HTML 中提取表格
- sql - 触发器一直无法编译。表存在时未找到索赔表
- perl - perl hash ref return: { 'a' =>1, % { sub() } }
- android - Android:找不到符号变量错误
- linux - 创建 ssh 用户,始终登录文件夹
- android - 无法使用 Firebase 云消息向 Android 设备发送推送通知