Concatenate each string element of one list to all elements of another list

Viewed 65
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?

1 Answers

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']
Related