[英]How do you extract all the elements of tuple from for loop?
I am trying to solve combinations(nCr) problem.我正在尝试解决组合(nCr)问题。 I have the following numbers
[1,2,3,4]
.我有以下数字
[1,2,3,4]
。 The code needs to produce all the possible combinations(4C2): (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)
.代码需要产生所有可能的组合(4C2):
(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)
。 Here is the code:这是代码:
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)
This is the output:这是输出:
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
Now I want the output values to be stored outside the for loop.现在我希望将输出值存储在 for 循环之外。 without overwriting the previous values.
不覆盖以前的值。
Is there a way to extract all the tuple( c
) elements outside the for-loop?有没有办法提取for循环之外的所有元组(
c
)元素? If not how do you extract it from list variable( c_listi
) outside the for-loop?如果不是,你如何从 for 循环外的列表变量(
c_listi
)中提取它?
If you assign the contents of itertools.combinations
to a variable as a list, you can reuse it as many times as you like:如果将
itertools.combinations
的内容作为列表分配给变量,则可以根据需要多次重用它:
cs = list(itertools.combinations(b_list,2))
If you need the contents to be lists, instead of tuples:如果您需要内容是列表,而不是元组:
cs = [list(t) for t in itertools.combinations(b_list,2)]
After either, you can use and reuse cs
as often as you like.之后,您可以根据需要随时使用和重用
cs
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.