Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Working with Lists
#3
You could remove the white space between the commas, but this doesn't look good and it's against PEP8.
As programmer we have some rules to follow. All languages does have this rules.

Looking at your values shows up a simple pattern.
First value: from 20 - 24 and repeats 5 times.
Second value: from 40 - 44 in a cycle

Instead of adding the values to the source code, you could it do programmatically.

from itertools import repeat, cycle


def range_repeater(start, end, repeats):
    for i in range(start, end):
      yield from repeat(i, repeats)


first = range_repeater(20, 25, 5)
second = cycle(range(40, 45))

result = [elements for elements in zip(first, second)]
print(result)
itertools is powerful.
repeat does what it sounds like: It repeats a value. The second argument defines how often.
cycle cycles through an iterable. When the iterable rises a StopIteration, the cycle begins from the start.

The yield from iterates over repeat until the repeat-generator is exhausted (repeasts == 5).
Then the next step in the for-loop does it for the next value from range.
The yield keyword converts the function into a generator. So calling the function, returns a generator,
which does nothing until you iterate over the generator. Super-short description. If you want to know more about this construct, you should look for better descriptions.

The line, where the result is constructed, is a list comprehension, which could also written in normal for-loop form:
result = []
for elements in zip(first, second):
    result.append(elements)
Instead of one line, you've 3 lines of code.

Finally you could bring your result in a better form to present it.
import pprint


pprint.pprint(result, compact=True)
Output:
[(20, 40), (20, 41), (20, 42), (20, 43), (20, 44), (21, 40), (21, 41), (21, 42), (21, 43), (21, 44), (22, 40), (22, 41), (22, 42), (22, 43), (22, 44), (23, 40), (23, 41), (23, 42), (23, 43), (23, 44), (24, 40), (24, 41), (24, 42), (24, 43), (24, 44)]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Working with Lists - by TheJax - Jan-23-2020, 01:17 AM
RE: Working with Lists - by michael1789 - Jan-23-2020, 03:03 AM
RE: Working with Lists - by DeaD_EyE - Jan-23-2020, 09:11 AM
RE: Working with Lists - by TheJax - Jan-23-2020, 02:08 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,341 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020