求助各位大神, 如何将(a,(b,(c,(d,(e,(f))))))转换为(f,(e,(d,(c,(b,(a))))))

2018-03-17 16:21:41 +08:00
 koplyp
7944 次点击
所在节点    Python
68 条回复
j0hnj
2018-03-17 17:35:33 +08:00
一个笨办法,但是能实现你的要求

def flatten(l):
ret = []
for elem in l:
if isinstance(elem, list):
ret.extend(flatten(elem))
else:
ret.append(elem)
return ret


def reconstruct(l):
inner = [l[0]]

for elem in l[1:]:
inner = [elem, inner]

return inner


if __name__ == '__main__':
print(reconstruct(flatten(['a', ['b', ['c', ['d', ['e', ['f']]]]]])))
j0hnj
2018-03-17 17:37:38 +08:00
排版乱了…看这里吧 https://paste.ubuntu.com/p/5F27Gybh4F/
whileFalse
2018-03-17 17:46:57 +08:00
source = ('a',('b',('c',('d',('e',('f'))))))
target = None
while True:
target = (source[0],) if target is None else (source[0], target)
if len(source) == 2:
source = source[1]
else:
break

print(target)
noNOno
2018-03-17 17:51:07 +08:00
替换掉字符串包含的括号,按字符串内字母(a,b,c,d,e,f)的字典顺序倒排,再按字符串长度加上括号,可以么
koplyp
2018-03-17 18:04:38 +08:00
感谢各位大佬,学习了
jorneyr
2018-03-17 18:09:06 +08:00
前后一起搜索,找到一对字符进行交换,然后继续搜索
haozhang
2018-03-17 18:32:30 +08:00
双栈运算了解一下
summerwar
2018-03-17 18:43:11 +08:00
import re
a = '(a,(b,(c,(d,(e,(f))))))'
re.sub(r'\((.*?),\((.*?),\((.*?),\((.*?),\((.*?),\((.*?)\)\)\)\)\)\)',r'(\6,(\5,(\4,(\3,(\2,(\1))))))',a)
ballshapesdsd
2018-03-17 18:47:26 +08:00
@summerwar #8 万一不是 6 个呢
summerwar
2018-03-17 18:58:39 +08:00
@ballshapesdsd 以此类推即可。

解决问题的关键是解决当下的,如果想写一个函数适用于所有情况,那是不可能的
yeeling
2018-03-17 19:11:16 +08:00
let a = '(a,(b,(c,(d,(e,(f))))))';
rst = a.substr(0,a.indexOf(')')).split(',').reverse().join(',') + a.substr(a.indexOf(')'));
console.log(rst);
这样呢
l1093178
2018-03-17 19:38:41 +08:00
ast.parse 了解一下?
rrfeng
2018-03-17 19:55:31 +08:00
不是双栈,是一个队列的事儿
az422
2018-03-17 20:39:50 +08:00
当作一个字符串,从头开始遍历,用数组 arr 记下字母的值。 再次遍历,判断是字母则反向插入 arr 各个值。
xrlin
2018-03-17 21:04:12 +08:00
楼上正解
SeanChense
2018-03-17 21:40:36 +08:00
入栈的时候去掉括号,再出栈配上括号就行了。
contmonad
2018-03-17 22:43:50 +08:00
任何函数式语言都自带这个操作:reverse
gowl
2018-03-17 22:47:13 +08:00
gowl
2018-03-17 22:49:54 +08:00
gowl
2018-03-17 22:52:01 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/438930

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX