3 回答
TA贡献1772条经验 获得超8个赞
一种快速的方法是使用zip逐个字符处理,并在每个位置取最大值;
arr = [' HHHHHHH HHHHHHHHHHH HHHHHHHHHHHHHHHHHHH ',
' E E EEE ',
' TT ',
' CC CCCC']
''.join(max(x) for x in zip(*arr))
' EHHHHHHHEHHHHHHHHHHHTTCCEEEHHHHHHHHHHHHHHHHHHHCCCC'
TA贡献1880条经验 获得超4个赞
像这样的东西?
array =[' HHHHHHH HHHHHHHHHHH HHHHHHHHHHHHHHHHHHH ',
' E E EEE ',
' TT ',
' CC CCCC']
result = []
for pos in zip(*array): # create tuples of chars from the same index in all strings
char = ''.join(pos).replace(' ', '') # remove all space chars
if char: # if there's anything left (ie. skip the char at index 0)
result.append(char[-1]) # then append the char from the array closest to the bottom
result = ''.join(result) # convert back to string
print result
哪个打印
EHHHHHHHEHHHHHHHHHHHTTCCEEEHHHHHHHHHHHHHHHHHHHCCCC
TA贡献1777条经验 获得超3个赞
这是一个numpy的解决方案:
>>> x
array([' HHHHHHH HHHHHHHHHHH HHHHHHHHHHHHHHHHHHH ',
' E E EEE ',
' TT ',
' CC CCCC'],
dtype='<U51')
>>> x.view('u4').reshape(len(x), -1).max(0).view(x.dtype).item(0).strip()
'EHHHHHHHEHHHHHHHHHHHTTCCEEEHHHHHHHHHHHHHHHHHHHCCCC'
时间:
f_pp 5.941 us
f_tb 27.473 us
f_ji 21.265 us
产生计时的代码:
import numpy as np
from timeit import timeit
x = np.array([' HHHHHHH HHHHHHHHHHH HHHHHHHHHHHHHHHHHHH ',
' E E EEE ',
' TT ',
' CC CCCC'])
def f_pp():
return x.view('u4').reshape(len(x), -1).max(0).view(x.dtype).item(0).strip()
def f_tb():
result = []
for pos in zip(*x): # create tuples of chars from the same index in all string
char = ''.join(pos).replace(' ', '') # remove all space chars
if char: # if there's anything left (ie. skip the char at index 0)
result.append(char[-1]) # then append the char from the array closest to the bottom
return ''.join(result) # convert back to string
def f_ji():
return ''.join(max(y) for y in zip(*x)).strip()
for f in (f_pp, f_tb, f_ji):
print(f.__name__, f'{timeit(f, number=1000) * 1000:>6.3f} us')
添加回答
举报