2

I'm trying to get:

 1    2    3    4    5    6    7    8    9   10
11   12   13   14   15   16   17   18   19   20
21   22   23   24   25   26   27   28   29   30
31   32   33   34   35   36   37   38   39   40
41   42   43   44   45   46   47   48   49   50
51   52   53   54   55   56   57   58   59   60
61   62   63   64   65   66   67   68   69   70
71   72   73   74   75   76   77   78   79   80
81   82   83   84   85   86   87   88   89   90
91   92   93   94   95   96   97   98   99  100

from this:

# nums is a range object
nums = list(range(1, 101))
chunks = []
print(nums)
print()

for i in range(0, len(nums), 10):
    chunks.append(nums[i:i+10])

in Python.... I can't for the life of me solve it.

1
  • You want to print the numbers that way or have a list of lists containing 10 numbers each? Commented Jul 2, 2016 at 6:44

2 Answers 2

1

You can just use nested loops to print chunks out like that. Here's an example:

for i in chunks:
    for j in i:
        print(j, end=" ")
    print()
Sign up to request clarification or add additional context in comments.

Comments

1

This should produce exactly the same output as in the question:

for chunk in chunks:
    print(''.join(str(x).rjust(5 if i else 2) for i, x in enumerate(chunk)))

Update: For every chunk it will first convert numbers to strings with str and then right justify them with rjust that uses space as default fill char. Since the first number on the row has width of 2 and rest of them have width of 5 enumerate is used to track the index so that correct argument can be passed to rjust. Enumerate returns tuples in form (index, item) and the index is then used in 5 if i else 2 to determine if number is first or not so width of 2 or 5 can be used respectively. Finally all the substrings are joined together for a row which is printed to screen.

5 Comments

this works perfectly, except that I have no idea why
Well, enumerate(chunk) creates a new list containing an index and the element for every element in the enumerated list... for i,x in loops through the enumerated list str(x) creates a string from a integer rjust adds spaces so that the string is (5 or 2) large, where (5 or 2) depends on the index in the enumeration (element 0 adds 5, all the other add 2). dont know if its clearer, but understand the steps, add this up, and you get how it works in total...
@RicardoMartinez Added a short explanation.
@SebastiaanMannem: Almost correct but you got the param passed to rjust wrong, 5 if i else 2 results to 2 in case i==0 and 5 in all other cases.
@ricardoMartinez: Would it help you if one was to change the one-liner into a block of code (maybe even with addition of some lines of comment)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.