简体   繁体   English

将一个列表的每个字符串元素连接到另一个列表的所有元素

[英]Concatenate each string element of one list to all elements of another list

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 Output 应该是一个列表

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?这个问题有没有更简单的解决方案?

You don't really need the week list.你真的不需要列表。 You can just calculate the week numbers as you go along.您可以像 go 一样计算周数。

You may not even need the year list if the range of years can be expressed with range()如果年份范围可以用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: Output:

['201901',
'201902',
...
'202251',
'202252']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查一个列表的每个元素是否是另一个列表的所有元素的倍数 - Check if each element of one list is a multiple of all the elements of another list 如何将字符串连接到字符串列表的每个元素? - How to concatenate a string to each element of a list of strings? 如何从另一个列表中的一个元素中减去列表中的所有元素? - How to subtract all elements in list from one element in another list? 将列表中的一个元素与另一个列表的所有元素进行比较 - Comparing one element from a list to ALL elements of another list 将列表的一个元素放在另一个列表的所有元素之间 - put one element of a list between all elements of another list 用另一个列表中的所有元素替换一个列表中的元素 - Replacing an element from one list with all elements in another list 将字符串连接到python中列表的所有元素的末尾 - Concatenate string to the end of all elements of a list in python 编写一个 Python 函数将给定列表的所有元素(最后一个元素除外)连接成一个字符串并返回该字符串 - Write a Python function to concatenate all elements (except the last element) of a given list into a string and return the string 将一个列表的字符串元素附加到 python 中每个子列表中另一个列表的 integer 元素 - attach the string element of one list to the integer element of another subsist of a list in each sub list in python 将列表中的每个元素与另一个元素进行比较 - Compare each of the elements of a list with another one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM