比较多个列表的大小

时间:2013-07-27 04:18:38

标签: python list python-2.7

假设我有多个列表:

A = [1]
B = [3, 2]
C = [5, 1, 6]
D = [7, 4, 18]

我想比较列表的长度,并输出4个列表的最长列表。 所以在这种情况下,输出将是:

A, D contain the longest list(s). 

我当时正在考虑逐一比较它们,但输入会非常繁忙且效率低下。有没有办法使用用户定义的函数?

我仍然是蟒蛇新手,我脑子里死了......

def fishing():
    global target_counter
    target_counter = pHands_new[target].count(target_rank)
    global card_counter

    if target_counter >0:
        for i in range(target_counter):
            pHands_new[target].remove(target_rank)
        for i in range(target_counter):
            pHands_new[N].append(target_rank)
        print "*"*70
        print "HIT:", target_counter, "card(s) transferred"
        print "*"*70
        card_counter = pHands_new[N].count(target_rank)
        if card_counter ==4:
            for i in range(card_counter):
                pHands_new[N].remove(target_rank)
            pBooks(N)
    else:
        draw = GetTopCard(sDeck_new)
        if draw == target_rank:
            pHands_new[N].append(draw)
            print "HIT: LUCKILY, You fished up the rank <"+draw+">"
            card_counter = pHands_new[N].count(draw)
            if card_counter ==4:
                for i in range(card_counter):
                    pHands_new[N].remove(draw)
                pBooks(N)

        elif draw != target_rank:
            pHands_new[N].append(draw)
            print "MISS: You fished up the rank <"+draw+">"
            card_counter = pHands_new[N].count(draw)
            if card_counter ==4:
                for i in range(card_counter):
                    pHands_new[N].remove(draw)
                pBooks(N)

def pBooks(player):
        books[player].append(target_rank)

注意:

-pHands_new是一个嵌套列表,pHands_new中有4个列表

-N是CURRENT播放器

-target_rank是针对其他玩家的卡

-Books是另一个嵌套列表。当玩家拥有4张相同的牌/等级时,它将从玩家手中移除并放入书中。

我在这里比较的列表是书籍[0] ......书籍[3]

1 个答案:

答案 0 :(得分:0)

>>> a = [1]
>>> b = [3, 2]
>>> c = [5, 1, 6]
>>> d = [7, 4, 18]
>>>
>>> max_len = len(max([a,b,c,d], key=len)) # max(map(len, [a,b,c,d]))
>>> lists = {
...     'a': a,
...     'b': b,
...     'c': c,
...     'd': d,
... }
>>> names = [name for name in lists if len(lists[name]) == max_len]
>>> print '{} contain the longest list(s).'.format(', '.join(names))
c, d contain the longest list(s).

>>> a = [1, 2, 3, 4]
>>> b = [3, 2]
>>> c = [5, 1, 6]
>>> d = [7, 4, 18]
>>> 
>>> max_len = len(max([a,b,c,d], key=len)) # max(map(len, [a,b,c,d]))
>>> lists = {
...     'a': a,
...     'b': b,
...     'c': c,
...     'd': d,
... }
>>> names = [name for name in lists if len(lists[name]) == max_len]
>>> print '{} contain the longest list(s).'.format(', '.join(names))
a contain the longest list(s).

books = [
    [1],
    [3, 2],
    [5, 1, 6],
    [7, 4, 18],
]

max_len = len(max(books, key=len)) # max(map(len, books))
names = [str(i+1) for i, bs in enumerate(books) if len(bs) == max_len]
print 'Book {} contain the longest list(s).'.format(', '.join(names))

# => Book 3, 4 contain the longest list(s).