Extract list element in Python

后端 未结 2 1883
我在风中等你
我在风中等你 2021-01-25 07:02

This is my first python program. I use the below code to generate combinations for a given range.

for k in range(0, items+1):        
    for r in range(0, item         


        
相关标签:
2条回答
  • 2021-01-25 07:26

    I initially posted this as a comment, but I think it's really an answer.

    You're misapplying itertools.combinations, and it's getting in the way of your ability to get your data in a convenient way. itertools.combination(range(k, r), r-k) is always going to yield exactly one value, range(k,r). That's unnecessary; you should just use the range directly.

    However, the for and if statements you use to produce your k and r values are a combination. Instead of the three levels of statements in your original code, you can use for k, r in itertools.combinations(range(items+1), 2). I suspect you were trying to do this when you put the itertools.combinations call in your code, but it ended up in the wrong place.

    So, to finally get around to your actual question: To access your data, you need to put all your items into a single data structure, rather than printing them. A list comprehension is an easy way to do that, especially once you've simplified the logic producing them, as my suggested changes above do:

    import itertools
    
    items = 4
    
    results = [range(k, r) for k,r in itertools.combinations(range(items+1),2)]
    print results
    # prints [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
    

    If you need to access the individual items, you use indexing into the results list, then into its member lists, as necessary.

    print results[6]    # prints [1, 2, 3]
    print results[6][0] # prints 1
    
    0 讨论(0)
  • 2021-01-25 07:34
    • a) Use indexes:

      >>> [(1, 2, 3)][0][0]
      1
      
    • b) I don't 100% understand this question, but instead of using a list comprehension as you have done, you can use list(itertools.combinations(...))

    • c) I think you are misunderstanding what map() does. map(str, [1, 2, 3]) is equivalent to:

      [str(i) for i in [1, 2, 3]]
      

    If you want to give [(0, 1)] a value, you can use a dictionary, but you have to use (0, 1) instead of [(0, 1)] because you would otherwise get TypeError: unhashable type: 'list'. If you want a "random value", I guess you can use the random module:

    import random
    {(0, 1) : random.randint(1,10)} # This is just an example, of course
    

    To store all the outputs in one list, you can use a massive list comprehension:

    >>> [list(itertools.combinations(range(x, i), i-x)) for x in range(0, items+1) for i in range(0, items+1) if (i-x) > 0]
    [[(0,)], [(0, 1)], [(0, 1, 2)], [(0, 1, 2, 3)], [(1,)], [(1, 2)], [(1, 2, 3)], [(2,)], [(2, 3)], [(3,)]]
    
    0 讨论(0)
提交回复
热议问题