首页 > 解决方案 > 如何根据位置值拆分列表元素

问题描述

我正在尝试从一组数字中分割年份、月份和控制数字。

s = ['201911007', '201203008']
my expected output
year=['2019', '2012']
month=['11','01']
controlnum=['007','008']

标签: pythonlistsplitintegercsv

解决方案


您可以使用列表推导生成每个部分的元组,然后 zip 将元组分解为单独的列表:

s = ['201911007', '201203008']

year,month,controlNum = map(list,zip(*( (v[:4],v[4:6],v[6:]) for v in s )))

输出:

print(year)
print(month)
print(controlNum)

['2019', '2012']
['11', '03']
['007', '008']

推荐阅读