2
year = ['2019', '2020', '2021', '2022']
week = [str(i).zfill(2) for i in range(1,53)]

I'm trying to join/concatenate each string element of year list to all elements of week list as follows

['201901'
'201902'
'201903'
.
.
.
.
.
'202250'
'202251'
'202252']
  • Output should be a list

I can achieve this using following code

week = [str(i).zfill(2) for i in range(1,53)]
year = [str(i) for i in range(2019,2023)]*len(range(2019,2023))*52
year.sort()
print({i:year.count(i) for i in year})

li = []
for yr in set(year):
    li.append([i + j for i, j in zip([k for k in year if yr in k], week)])
yr_week_id = sorted(list(np.concatenate(li)))
print(yr_week_id)

Is there any simpler solution to this problem?

Suhas_Pote
  • 3,620
  • 1
  • 23
  • 38
  • 3
    `[year + weak for year in map(str, range(2019, 2023)) for weak in map('{0:>02}'.format, range(1, 53))]` or `[f'{year}{weak:>02}' for year in range(2019, 2023) for weak in range(1, 53)]` – Mechanic Pig Sep 02 '22 at 16:50
  • 2
    Similar: `[str(year) + str(weak).rjust(2,'0') for year in range(2019, 2023) for weak in range(1, 53)]` – treuss Sep 02 '22 at 16:51
  • Does this answer your question? [Concatenate strings from the cartesian product of two list (preferably without for loop)](https://stackoverflow.com/questions/65484461/concatenate-strings-from-the-cartesian-product-of-two-list-preferably-without-f) – Abdul Aziz Barkat Sep 02 '22 at 17:16

1 Answers1

0

You don't really need the week list. You can just calculate the week numbers as you go along.

You may not even need the year list if the range of years can be expressed with range()

year = ['2019', '2020', '2021', '2022']
output = []
for yy in year:
    output.extend([f'{yy}{ww:02d}' for ww in range(1, 53)])
print(output)

Output:

['201901',
'201902',
...
'202251',
'202252']
DarkKnight
  • 19,739
  • 3
  • 6
  • 22