Python 串联

-4 投票
5 回答
4525 浏览
提问于 2025-04-16 21:20

这个问题可能看起来很简单,但我就是搞不明白 -

我现在有这些值:['2000']['09']['22']

我想要的结果是:20000922 或者 '20000922'

代码

def transdatename(d):
    year = re.findall('\d\d\d\d', str(d))
    premonth = re.findall('[A-Z][a-z]{2,9}', str(d))
    month = replace_all(str(premonth), reps)
    daypre = re.findall('\d{1,2},', str(d))
    day = re.sub(',','', str(daypre))
    fulldate = str(year)+str(month)+str(day)
    return fulldate

示例数据

输入: ['\nSeptember 23, 2000']

期望输出: '20000922'

5 个回答

2

使用 itertools.chain

from itertools import chain    
data = [['2000'],['09'],['22']]   
''.join(chain(*data))
#OR
int(''.join(chain(*data))) # for numeric value representation

或者使用 functools.reduce

data = [['2000'],['09'],['22']]   
''.join(reduce(lambda res,x: res+x, data))

还有:

''.join(''.join(x) for x in data)

至少在你提到列表、元组或列表的集合时:

initList = [['2000'],['09'],['22']]   
resultList = []
for subList in initList:
   resultList.append(''.join(subList))

outputValue = ''.join(resultList)
intValue = int(outputValue)

看完你的代码,我觉得可以这样做:

str_dates = ['\nSeptember 23, 2000']
monthMap = {'January': 1, 'February': 2, ....}
month, day, year str_dates[0].lstrip('\n').split()
year + monthMap[month] + day[:-1]

或者 - 我认为这是最好的方法:

from datetime import datetime
str_dates = ['\nSeptember 23, 2000']
[datetime.strptime(sDate,'%B %d, %Y').strftime('%Y%d%m') for sDate in str_dates]

当然你可以使用正则表达式 - 但我不确定这是否是最合适的方法,不过如果你想用的话,最好使用单个的,像这样(这只是个示例代码,应该有更好的正则表达式):

yearData = re.findall(r'(?i)^([a-z]{2,9})\s(\d{1,2}),\s(\d{2,4}$)', 'September 23, 2000')
#yearData contains now [('September', '23', '2000')]
2

我猜这些是列表项吧?

a=['2000']
b=['99']
c=['22']

如果没错的话,

a[0]+b[0]+c[0]

这样就可以解决问题了。

4

你是在尝试这样做吗?

>>> input= '\nSeptember 23, 2000'
>>> format= '\n%B %d, %Y'
>>> datetime.datetime.strptime(input,format)
datetime.datetime(2000, 9, 23, 0, 0)
>>> (_+datetime.timedelta(-1)).strftime("%Y%m%d")
'20000922'

如果是的话,那你把事情搞得太复杂了。

撰写回答