Extract list element in Python

后端 未结 2 1921
我在风中等你
我在风中等你 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
    

提交回复
热议问题