开发者

Functional append/extend

The methods append and extend in Python are not functional by nature, they modify the callee and return None.

Is there an alternative way to do what these methods do and get a new list as a returned value?

Consider this example:

def myfun(first, *args):
  for elem in [first].extend(a开发者_运维百科rgs):
    print elem

Obviously, this won't work.

Is there a way to construct a new list directly with an expression, instead of being forced to write the following?

def myfun(first, *args):
   all_args = list(first)
   all_args.extend(args)

   for elem in all_args:
     print elem

Thanks.


>>> def append(lst, elem):
...     return lst + [elem]
... 
>>> append([1, 2, 3], 4)
[1, 2, 3, 4]
>>> def extend(lst1, lst2):
...   return lst1 + lst2
... 
>>> extend([1, 2], [3, 4])
[1, 2, 3, 4]

Is that what you wanted?

You may also define your own type, which returns the list itself on these operations, in addition to change:

>>> class MyList(list):
...   def append(self, x):
...     super(MyList, self).append(x)
...     return self
...   def extend(self, lst):
...     super(MyList, self).extend(lst)
...     return self
... 
>>> l = MyList([1, 2, 3])
>>> l.append(4)
[1, 2, 3, 4]
>>> l.extend([5, 6, 7])
[1, 2, 3, 4, 5, 6, 7]
>>> l
[1, 2, 3, 4, 5, 6, 7]


You can rewrite that as:

[first] + args
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜