简体   繁体   English

你如何从for循环中提取元组的所有元素?

[英]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.

相关问题 python-如何将元素存储在元组中 - python - how do you store elements in a tuple 如何从python列表中的元素中提取浮点数? - How do you extract the floats from the elements in a python list? Python从元组列表中提取元素 - Python extract elements from list of tuple Python - 如何从列表中提取元组? - Python - how do I extract a tuple from a list? 如何使用while循环在由制表符分隔的一行上显示切片中的所有元素 - How do you use a while loop to display all elements in the slice on one line separated by tabs 遍历文件夹结构并从所有 xml 文件中提取元素 - Loop over folder structure and extract elements from all xml files 如何在Python中检查元组的所有元素是否是其他元组的元素? - How to check if all elements of a tuple are elements of other tuple in python? 如何从值是 Python 中的 2D 列表的字典中有效地提取列中的所有元素? - How do I efficiently extract all elements in a column from a dictionary whose values are 2D lists in Python? 如何使用 for 循环在新行上打印出 Numpy 数组中的元素? - How do you print out elements from a Numpy array on new lines using a for loop? 如何将包含三个元素的元组转换为包含一个键和两个值的字典? - How do you turn a tuple with three elements into a dictionary containing a key and two values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM