2
A
回答
3
运行这一系列更新换代:
(
- ><ul><li>
)
- ></ul></li>
,
- ></li><li>
然后在浏览器
打开它,或者如果它是一个Python对象,使用pprint:
>>> x = ((("A","B"),("C","D")),"E")
>>> from pprint import pprint
>>> pprint(x, width=1)
((('A',
'B'),
('C',
'D')),
'E')
或自定义的Python的解决方案:
from itertools import izip
def first_then(first, then):
yield first
while True:
yield then
def tree_lines(x):
if type(x) is tuple:
if len(x) == 1:
# singular tuple
for p, l in izip(first_then('--', ' '), tree_lines(x[0])):
yield p + l
else:
first, rest, last = x[0], x[1:-1], x[-1]
# first entry
for p, l in izip(first_then('T-', '| '), tree_lines(first)):
yield p + l
# middle entries
for y in rest:
for p, l in izip(first_then('>-', '| '), tree_lines(y)):
yield p + l
# last entries
for p, l in izip(first_then('L-', ' '), tree_lines(last)):
yield p + l
else:
yield str(x)
x = ((('A','B'),('C','D')),'E')
for l in tree_lines(x):
print(l)
2
前阵子我写了一些用于制作树木文本表示的东西。这可能适合在这里。
class Node:
def __init__(self, value):
self.value = value
self.children = []
pipe = chr(179)
t = chr(195)
l = chr(192)
backwards_r = chr(191)
def printable(node, seq_is_last_child = []):
"""returns a string representation of the given node"""
ret = ""
if seq_is_last_child:
for b in seq_is_last_child[:-1]:
if b:
ret = ret + " "
else:
ret = ret + pipe + " "
if seq_is_last_child[-1]:
ret = ret + l + " "
else:
ret = ret + t + " "
ret = ret + node.value
for idx, c in enumerate(node.children):
ret = ret + "\n" + printable(c, seq_is_last_child + [idx == len(node.children)-1])
return ret
def make_node(t):
"""creates a Node system from a nested tuple"""
ret = Node(backwards_r)
for child in t:
if isinstance(child, str):
ret.children.append(Node(child))
else:
ret.children.append(make_node(child))
return ret
x = ((('A','B'),('C','D')),'E')
print printable(make_node(x))
结果:
┐
├ ┐
│ ├ ┐
│ │ ├ A
│ │ └ B
│ └ ┐
│ ├ C
│ └ D
└ E
编辑:Unicode版本:
class Node:
def __init__(self, value):
self.value = value
self.children = []
def printable(node, seq_is_last_child = []):
"""returns a string representation of the given node"""
ret = ""
if seq_is_last_child:
for b in seq_is_last_child[:-1]:
if b:
ret = ret + " "
else:
ret = ret + "│ "
if seq_is_last_child[-1]:
ret = ret + "└ "
else:
ret = ret + "├ "
ret = ret + node.value
for idx, c in enumerate(node.children):
ret = ret + "\n" + printable(c, seq_is_last_child + [idx == len(node.children)-1])
return ret
def make_node(t):
"""creates a Node system from a nested tuple"""
ret = Node("┐")
for child in t:
if isinstance(child, str):
ret.children.append(Node(child))
else:
ret.children.append(make_node(child))
return ret
x = ((('A','B'),('C','D')),'E')
print printable(make_node(x))
1
可以使用迭代函数,发现depth
和每个点的height
:
def locate(xs, depth, cnt):
from functools import partial
if isinstance(xs, str):
return dict(depth=depth, height=- next(cnt), inner=None, txt=xs)
else:
fn = partial(locate, depth=depth+1, cnt=cnt)
loc = list(map(fn, xs))
height = np.mean([x['height'] for x in loc])
return dict(depth=depth, height=height, inner=loc, txt=None)
以上函数返回一个字典,我们需要这走通过这本字典和情节的每个节点上的另一个功能:
def walk(loc, ax):
col, lw = 'DarkBlue', 2
x, y, inner, txt = map(loc.get, ['depth', 'height', 'inner', 'txt'])
if not inner:
ax.text(x, y, ' ' + txt, ha='left', va='center', size='large')
return y
else:
ys =[walk(t, ax) for t in inner]
for y1 in ys:
ax.plot([x, x+1], [y1, y1], color=col, linewidth=lw)
ax.plot([x, x], [min(ys), max(ys)], color=col, linewidth=lw)
return y
的location
功能是在顶层通过传递count
迭代器调用,返回一个词典,其包括所有必要的信息来绘制每个级别:
from itertools import count
xs = ((('A','B'),('C','D')),'E',)
loc = locate(xs, 0, count())
具有轴线沿着该字典被传递到walk
功能:
fig = plt.figure(figsize=(2, 3))
ax = fig.add_axes([.05, .05, .9, .9])
walk(loc, ax)
plt.axis('off')
xl, yl = ax.get_xlim(), ax.get_ylim()
ax.set_xlim(xl[0] - .05, xl[1] + .05)
ax.set_ylim(yl[0] - .05, yl[1] + .05)
其结果将是:
另一个例子:
xs = ((('A','B','C','D'),('E'),('F1','F2'),'G'),(('H1','H2'),('I','J','K'),'L'))
1
使用SciPy的的cluster.hierarchy.dendrogram:
import re
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as hier
import scipy.spatial.distance as dist
import itertools as IT
def parse_nested(text, left=r'[(]', right=r'[)]', sep=r','):
""" http://stackoverflow.com/a/17141899/190597 (falsetru) """
pat = r'({}|{}|{})'.format(left, right, sep)
tokens = re.split(pat, text)
stack = [[]]
for x in tokens:
if not x: continue
if re.match(sep, x): continue
if re.match(left, x):
stack[-1].append([])
stack.append(stack[-1][-1])
elif re.match(right, x):
stack.pop()
if not stack:
raise ValueError('error: opening bracket is missing')
else:
stack[-1].append(x)
if len(stack) > 1:
print(stack)
raise ValueError('error: closing bracket is missing')
return stack.pop()
def place_points(datalist, x=IT.count(), y=1):
retval = []
for item in datalist:
if isinstance(item, list):
next(x)
retval.extend(place_points(item, x=x, y=y*2.5))
else:
retval.append([item, (next(x), y)])
return retval
# data = '(((A,B,G),(C,D,F)),(E,(H,I,J,(K,L,M,N))))'
data = '((A,B),(C,D),E)'
labels, points = zip(*place_points(parse_nested(data)))
d = dist.pdist(points)
linkage_matrix = hier.linkage(d)
P = hier.dendrogram(linkage_matrix, labels=labels)
plt.show()
相关问题
- 1. {a,b,c,d,e} a,b-> c,a,b-> d和d-> e的最高范式是什么?
- 2. 如何用“d”替换“a”,用“e”替换“b”,用“f”替换“c”。 。 。 “x”带“a”,“y”带“b”,“z”带“c”?
- 3. A,B,C,D分组内的不同的E,F?
- 4. 加入2所列出得到(A,d,B,E,C,F),而不是(A,B,C,d,E,F)
- 5. 使用java将字符串[] str = {“a”,“b”,“c”,“d”,“e”,“f”}映射为{a = b,c = d,e = f}流
- 6. PIL透视变换,找出(a,b,c,d,e,f,g,h)
- 7. Bootstrap中的“Pull center”:A -D- B -E- C列收缩到A-B-C // D-E,如何在D和E之间获得B?
- 8. 如何计算SonarQube A,B C,D和E评分?
- 9. 如何写A :: B :: C => D给定A :: B :: C和(A,B,C)=> D?
- 10. 如果我有关系R(A,B,C,D,E)和FD是A→C,AB→D,CD→E,E完全依赖于AB?
- 11. SQL条件:(A = B AND C LIKE%D%)或(A LIKE%B%和C = D)
- 12. 在c编程(A^B^C)/(D * E)中插入后缀转换
- 13. 如何完成A,B,C,D,E的具体活动?
- 14. PHP,如果A则B和C别的d和E
- 15. 如何优化查询,如select * from(where,a,b,c,d,e,f ....)中的字段?
- 16. 正常化具有5个属性A,B,C,D和E的表格
- 17. 合并路径与Python,从/ A/B/C + C/d到/ A/B/C/d
- 18. ORMlite QueryBuilder其中A和B和C和(D或E或F)
- 19. 当Alphabates(A,B,C,D,E,F)出现在号码
- 20. 简化布尔表达式(a *'b *'c)+('a *'b * c)+('a * b *'c)+(a *'b * c)
- 21. 为什么alert([“a”,“b”,“c”,“d”,“e”] [[1,2],3,4])在javascript中输出e?
- 22. 查找函数I(a,b,c,d)积分的四维最小值(a,b,c,d)
- 23. 简化(a + b)XOR(c + b)
- 24. 从5,2,20,6,6到B,A,D,C,C
- 25. 如何标准化范围[a,b]到[c,d],其中a映射到d,b映射到c
- 26. 对于A,B在C,d的Python
- 27. 从{a-b,b-c,c-a}改变为{(a,b),(b,c),(c,a)}?
- 28. 对称字典其中d [a] [b] == d [b] [a]
- 29. 替代B = A(:)在Matlab
- 30. 如何分隔CSV分隔数据并相应存储值?</p> <pre> A,B,C,D B,C,D,E C,D,E,F D,E,F,G . . . </pre> <p>虽然我想在下面的方式做,我丢失:
也许你应该使用unicode。在我的机器上'chr(179)=='³''。 ASCII是7位,只能达到127. – Hyperboreus
@Hyperboreus,你是对的。我已经添加了一个Unicode版本。 – Kevin