【问题标题】:How to print all number combinations from specific set of numbers?如何打印特定数字集中的所有数字组合?
【发布时间】:2019-10-17 06:43:10
【问题描述】:

我正在尝试从数字列表中获取每个数字组合。

目前我可以轻松地将其作为一个范围,并且我可以在一组 5 个数字中获得我想要的每个数字组合(打印在 5 个单独的列中)。我不知道该怎么做是如何从一个非常具体的数字列表中获取每个数字组合,这些数字列表从现有代码中打印出完全相同的格式。

下面是我在一个范围内查找数字的代码,它运行良好:

for range_numbers in combinations(list(range(1,20)), 5): #This gives me every 5 number combination without repeating numbers.
    for nums in combinations(list(range(1,10)), 1): #this adds every combination of this range without repeating numbers, in a single column.
        combined = range_numbers + nums
        file_writer.writerow(combined)
        count += 1

我想要的是产生完全相同的结果,但来自特定数字的列表,例如 5 个数字组合的 [2,3,5,7,9,12,13,15,19] 和 [3 ,7,8,10] 表示添加的 1 个数字组合。

感谢任何帮助,我在过去的 8 小时里一直在谷歌上搜索并试图弄清楚这一点,感觉应该很容易,但我的大脑现在只是糊状..

【问题讨论】:

    标签: python list numbers range combinations


    【解决方案1】:

    这是操作数的直接替换:

    from itertools import combinations, product
    large = [2,3,5,7,9,12,13,15,19]
    small = [3,7,8,10]
    
    for range_numbers in combinations(large, 5):
        for nums in combinations(small, 1):
            ...
    

    也许更好,使用 product 在单个循环中执行此操作,正如 Guido 的意图:

    for combined in product( [list(combinations(large, 5)),
                              list(combinations(small, 1))] ):
    

    【讨论】:

    • 这太完美了!!!太感谢了!在某件事上花上一整天,让它在 0.4388279914855957 秒内完成任务,真是太神奇了,哈哈哈非常感谢!
    • 不客气。 小心列表大小。如果您的列表很长,请查找 chain 方法以链接 combinationsproduct 生成器。
    • 好棒!非常感谢您的建议!我来看看chain方法。
    猜你喜欢
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多