Python排序列表,包含两个使用列表中的所有整数

时间:2015-07-07 05:56:07

标签: python list sorting recursion

我如何编写一个消耗两个列表的递归函数,然后生成一个包含两个列表中元素的列表?如果两个列表各有两个数字,则生成的列表中也会有两次该数字。 这就是我到目前为止所做的:

def merge(L1, L2, i, j, R): if L1[i] == L2[j]: R.append(L1[i]) R.append(L2[j]) merge(L1, L2, i, j+1, R) else: merge(L1, L2, i+1, j, R)
def sorted_intersection(lst1, lst2): R = [] return merge(lst1, lst2, lst1[0], lst2[0], R)

Nvm,想出了代码。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

请参阅模块collections的文档,其中包含许多功能任务的帮助程序:

from collections import defaultdict, Counter

# Preserves the order of b:
def in_both(a, b):
    # Count the occurrences of elements in a:
    a = Counter(a)
    # Default to 0:
    a = defaultdict(lambda: 0, a)

    # Return true if there is a positive amount of items x in a left:
    def take_from_a(x):
        cur = a[x]
        if cur > 0:
            a[x] = cur - 1
            return True

    # Filter out elements in b that are not often enough in b:
    return filter(take_from_a, b)

in_both("abbcccdddd", "abcdabcde") == "abcdbcd"

此处ab都会迭代一次。

答案 1 :(得分:0)

为什么递归?

a = [1, 2, 2, 3, 3] 
b = [2, 3, 4] 

result = [[x, b.remove(x)][0] for x in a if x in b] 
result
[2, 3, 3]

答案 2 :(得分:-1)

递归听起来像是一种非蟒蛇式的做法。简单的事情怎么样:

def signup(req):
    if req.method == 'POST':
        ...
        sf = SignupForm(req.POST)
        # print sf.data
        # <QueryDict: {u'csrfmiddlewaretoken': [u'U0M9skekfcZiyk0DhlLVV1HssoLD6SGv'], u'password': [u''], u'email': [u'hello']}>
        email = sf.data.get("email", '')
        password = sf.data.get("password", '')
        ...

产生:c = [1,2,3,2,3,4]