【问题标题】:How do you extract all the elements of tuple from for loop?如何从 for 循环中提取元组的所有元素?
【发布时间】:2020-02-21 00:03:24
【问题描述】:

我正在尝试解决组合(nCr)问题。我有以下号码[1,2,3,4]。代码需要产生所有可能的组合(4C2):(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)。这是代码:

import itertools
from math import factorial

def calc_combin(n, r):
    return factorial(n) // factorial(r) // factorial(n-r)

lines=calc_combin(4,2) #4C2

b_list = list(range(1,5))
combinations = itertools.combinations(b_list,2)

c_list=[]

for i_c in range(0,lines):
    c_list.append([])

for c in combinations:
    c                 #tuple that has all the combinations
    c_listi = list(c) #converting tuple "c" to list "c_listi"
    print(c_listi)

这是输出:

[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]

现在我希望将输出值存储在 for 循环之外。不覆盖以前的值。

有没有办法在 for 循环之外提取所有 tuple(c) 元素?如果不是,您如何从 for 循环外的列表变量(c_listi)中提取它?

【问题讨论】:

  • 尝试将迭代器直接转换为列表:list(itertools.combinations(...))

标签: python list for-loop tuples combinations


【解决方案1】:

如果您将itertools.combinations 的内容作为列表分配给一个变量,您可以多次重复使用它:

cs = list(itertools.combinations(b_list,2))

如果您需要内容是列表,而不是元组:

cs = [list(t) for t in itertools.combinations(b_list,2)]

之后,您可以随意使用和重复使用cs

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 2017-11-16
    • 2021-06-08
    • 2021-07-31
    • 2021-12-05
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多