这是我从我的一个评论包中得到的一个问题,我很难过。这是描述
“返回m个字符串的列表,其中m是最长字符串的长度 在strlist中,如果strlist不为空,则返回第i个字符串 由strlist中每个字符串的第i个符号组成,但仅来自 具有第i个符号的字符串,顺序对应于 strlist中字符串的顺序。 如果strlist不包含非空字符串,则返回[]。“
这是示例
转置(['transpose','','list','of','strings'])
['tlos','rift','asr','nti','sn','pg','os','s','e']
这是你要遵循的给定格式/风格
# create an empty list to use as a result
# loop through every element in the input list
# loop through each character in the string
# 2 cases to deal with here:
# case 1: the result list has a string at the correct index,
# just add this character to the end of that string
# case 2: the result list doesn't have enough elements,
# need to create a new element to store this character
我得到了“处理这里的2个案件:”部分,然后我卡住了,这是我到目前为止的事情
result = []
for index in strlist:
for char in range (len(index)):
答案 0 :(得分:-1)
这应该有效:
def transpose(strlist):
# create an empty list to use as a result
result = []
# loop through every element in the input list
for i in range(len(strlist)):
# loop through each character in the string
for j in range(len(strlist[i])):
# 2 cases to deal with here:
if len(result) > j:
# case 1: the result list has a string at the correct index,
# just add this character to the end of that string
result[j] = result[j] + strlist[i][j]
else:
# case 2: the result list doesn't have enough elements,
# need to create a new element to store this character
result.append(strlist[i][j])
return result
print(transpose(['transpose', '', 'list', 'of', 'strings']))
输出:['tlos', 'rift', 'asr', 'nti', 'sn', 'pg', 'os', 's', 'e']
有更多pythonic方法可以实现它,但显示的代码符合您给定的格式/样式