0

假设我有多个列表:

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

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

A, D contain the longest list(s). 

我正在考虑将它们一一进行比较,但是打字会非常忙碌且效率低下。有没有办法使用用户定义的函数来做到这一点?

我对python还是很陌生,我要脑死了......

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 是当前玩家

-target_rank 是其他玩家的目标卡

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

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

4

1 回答 1

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).
于 2013-07-27T04:22:39.103 回答