我的目标是接收一个列表,然后向后输出。 现在我的输入/输出是:
['1', '[2,[4,5]]', '3']
['3', '[]5,4[,2]', '1']
从输出中可以看出,括号朝向错误的方向。我试图使用replace函数,但它用括号替换每个位置。你知道吗
正确的输出应该如下所示。你知道吗
['3', '[[5,4],2]', '1']
这是我的密码。你知道吗
organizeList = ['1','[2,[4,5]]','3']
print("Format should be similar to '1, 2, [3, 4], 5'")
#organizeList.append(input("Enter a list: ")
tempList = []
otherList = []
testString = ""
lastString = ""
print(organizeList)
for p in range(len(organizeList)-1, -1, -1):
if (organizeList[p].startswith('[') == True):
for showList in organizeList[p]:
testString = testString + showList
for x in range(len(testString)-1, -1, -1):
if (testString[x] == ']'):
testString = testString.replace(testString[x], '[')
elif (testString[x] == '['):
testString = testString.replace(testString[x], ']')
lastString = lastString + testString[x]
tempList.append(lastString)
else:
tempList.append(organizeList[p])
print(tempList)
我还在学习python,所以如果您对如何清理我的代码有任何提示和窍门,请告诉我。你知道吗
你也可以这样试试
样本输入/输出
我不知道你的代码有什么问题,但是你应该把左括号重新映射到右括号,反之亦然,就像这样:
我能做一个相当简单的修复。不确定我的整个方法是否正确,但这是有效的。你知道吗
就像我说的,我还在学习python,所以如果有人对我有什么建议,请告诉我。你知道吗
相关问题 更多 >
编程相关推荐