[英]How to split list element according to place value
我正在嘗試從一組數字中分割年份、月份和控制數字。
s = ['201911007', '201203008']
my expected output
year=['2019', '2012']
month=['11','01']
controlnum=['007','008']
您可以使用列表理解來生成每個部分的元組,然后 zip 將元組分解為單獨的列表:
s = ['201911007', '201203008']
year,month,controlNum = map(list,zip(*( (v[:4],v[4:6],v[6:]) for v in s )))
output:
print(year)
print(month)
print(controlNum)
['2019', '2012']
['11', '03']
['007', '008']
s = ['201911007', '201203008']
year = []
month = []
controlnum = []
for number in s:
year.append(number[:4])
month.append(number[4:6])
controlnum.append(number[6:])
print(year)
print(month)
print(controlnum)
嘗試使用 function
s = ['201911007', '201203008']
def info(s):
return [i[:4] for i in s], [i[4:s] for i in a], [i[6:] for i in s]
year, month, controlnum = defo(s)
print (year)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.