[英]Changing certain characters in a list at a specific position
我的目标是获取列表,然后向后输出。 现在我的输入/输出是:
['1', '[2,[4,5]]', '3']
['3', '[]5,4[,2]', '1']
从输出中可以看到,括号朝向错误的方向。 我正在尝试使用替换功能,但是它将每个位置替换为括号。
正确的输出应如下所示。
['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,因此,如果您还有关于如何清理代码的任何提示和技巧,请告诉我。
我不知道您的代码有什么问题,但是您应该将所有左括号重新映射为右括号,反之亦然,如下所示:
>>> remap = {ord('['): ']', ord(']'): '['}
>>> L = ['1', '[2,[4,5]]', '3']
>>> [s[::-1].translate(remap) for s in reversed(L)]
['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 = ""
remap = {ord('['): ']', ord(']'): '['}
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] == ']'):
lastString = lastString + '['
elif (testString[x] == '['):
lastString = lastString + ']'
else:
lastString = lastString + testString[x]
tempList.append(lastString)
else:
tempList.append(organizeList[p])
print(tempList)
就像我说的我仍在学习python,所以如果有人对我有任何提示,请告诉我。
您也可以尝试这种方式
my_list_of_string = ['1', '[2,[4,5]]', '3']
print("Input : ",my_list_of_string)
# This function basically replace '[' to ']' and ']' to '['
# That's why when we will reverse the string it will maintain the
# parenthesis
def reverse_list_string(ls):
c = []
for ch in ls:
if ch == "[":
c.append("]")
elif ch == "]":
c.append("[")
else:
c.append(ch)
c.reverse()
new_reverse_string = "".join(c)
return new_reverse_string
reverse_ls=[]
for ls in my_list_of_string:
new_string = reverse_list_string(ls)
reverse_ls.append(new_string)
reverse_ls.reverse()
print("Output : ", reverse_ls)
样本输入/输出
Input : ['1', '[2,[4,5]]', '3']
Output : ['3', '[[5,4],2]', '1']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.