Extract list element in Python

后端 未结 2 1878
我在风中等你
我在风中等你 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: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,)]]
    

提交回复
热议问题