<p>您可以使用<code>isinstance()</code>来检查<code>llist</code>中值的类型,并相应地执行操作。递归基本上是免费的,通过构造函数实现的。你知道吗</p>
<pre><code>from collections import Iterable # Using Python 2.7
class Linked_list:
def __init__(self, llist=None):
... # Same as your code.
if llist is not None:
for i in llist:
if isinstance(i, basestring):
ll = Linked_list()
for c in i:
ll.append(c)
self.append(ll)
elif isinstance(i, Iterable):
self.append(Linked_list(i))
else:
self.append(i)
...
def __repr__(self):
xs = []
nd = self.head
while nd is not None:
xs.append(nd.data)
nd = nd.next
return repr(xs)
a = Linked_list([1, 2, Linked_list(range(5)), Linked_list(range(3))])
b = Linked_list([1, 2, list(range(5)), list(range(3))])
c = Linked_list([1, 2, (0, 1, 2, 3, 4), (0, 1, 2)])
d = Linked_list([1, 2, (0, 1, range(4), 3, 4), (0, 1, [4,5,'abc'])])
print a
print b
print c
print d
</code></pre>
<p>输出:</p>
<pre><code>[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, [0, 1, 2, 3], 3, 4], [0, 1, [4, 5, ['a', 'b', 'c']]]]
</code></pre>