Python 通过检查索引是否存在,然后更新,将项目添加到列表中
这是我在一个审查包中提出的一个问题,我很困惑。这是描述 返回m个字符串的列表,其中m是最长字符串的长度 在strlist中,如果strlist不是空的,则返回第i个字符串 由strlist中每个字符串的第i个符号组成,但仅由 具有第i个符号的字符串,其顺序与 strlist中字符串的顺序。 如果strlist不包含非空字符串,则返回[]。“ 这就是一个例子 转置(['transpose','','list','of','strings']) ['tlos','rift','asr','nti','sn','pg','os','s','e'] 这就是你必须遵循的既定格式/风格Python 通过检查索引是否存在,然后更新,将项目添加到列表中,python,function,Python,Function,这是我在一个审查包中提出的一个问题,我很困惑。这是描述 返回m个字符串的列表,其中m是最长字符串的长度 在strlist中,如果strlist不是空的,则返回第i个字符串 由strlist中每个字符串的第i个符号组成,但仅由 具有第i个符号的字符串,其顺序与 strlist中字符串的顺序。 如果strlist不包含非空字符串,则返回[]。“ 这就是一个例子 转置(['transpose','','list','of','strings']) ['tlos','rift','asr','nti',
# 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
我谈到了“这里要处理的两个案例:”部分,然后我被卡住了,这就是我到目前为止所拥有的
result = []
for index in strlist:
for char in range (len(index)):
这应该起作用:
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']
有更多类似python的方法来实现它,但是显示的代码与给定的格式/样式相匹配现在不要担心遵循“格式/样式”,只需尝试先做一些有效的东西。然后把它贴在这里。