列表/双端队列和嵌套循环

0 投票
2 回答
534 浏览
提问于 2025-04-18 10:34

我刚开始学习Python,遇到了一些问题。我在用Python 3,下面是我的代码:

from collections import deque

databases=input("Enter databases: ")

db_list = deque(databases.split())
node1list = []
node2list = []
node3list = []

numDatabases = len(db_list)

while len(db_list) > 0:
    if len(db_list) > 0:
        node1list.append(db_list.popleft())
    if len(db_list) > 0:
        node2list.append(db_list.popleft())
    if len(db_list) > 0:
        node3list.append(db_list.popleft())

print("Paste the following in Node 1's file")
print("--------------------------------------------")
print("[[INSTANCE]")
print("#  Keep a blank space after the colon character.")
print("#")
print("group1:", end="")
for db in node1list:
    print(" " + db, end="")

print("\n\nPaste the following in Node 2's file")
print("--------------------------------------------")
print("[[INSTANCE]")
print("#  Keep a blank space after the colon character.")
print("#")
print("group1: ", end="")
for db in node2list:
    print(" " + db, end="")

print("\n\nPaste the following in Node 3's file")
print("--------------------------------------------")
print("[[INSTANCE]")
print("#  Keep a blank space after the colon character.")
print("#")
print("group1: ", end="")
for db in node3list:
    print(" " + db, end="")

当我运行这段代码时,输出结果是这样的:

Enter databases: one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone twentytwo twentythree twentyfour twentyfive twentysix twentyseven twentyeight twentynine thirty thirtyone thirtytwo thirtythree thirtyfour
----------------------------------------------------------------------------------------------

Paste the following in Node 1's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group1: one four seven ten thirteen sixteen nineteen twentytwo twentyfive twentyeight thirtyone thirtyfour

Paste the following in Node 2's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group1:  two five eight eleven fourteen seventeen twenty twentythree twentysix twentynine thirtytwo

Paste the following in Node 3's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group1:  three six nine twelve fifteen eighteen twentyone twentyfour twentyseven thirty thirtythree

但是我希望group1最多只能包含5个数据库,然后自动开始把剩下的数据库放到group2里。每个组最多也只能放5个数据库。而且,数据库的数量可能远不止34个(这个数字是个未知数),所以我需要能够不断增加组的数量来适应这个未知的数量。

所以我希望输出结果看起来像这样:

Enter databases: one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twentyone twentytwo twentythree twentyfour twentyfive twentysix twentyseven twentyeight twentynine thirty thirtyone thirtytwo thirtythree thirtyfour

----------------------------------------------------------------------------------------------

Paste the following in Node 1's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group1: one four seven ten thirteen
group2: sixteen nineteen twentytwo twentyfive twentyeight
group3: thirtyone thirtyfour

Paste the following in Node 2's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group1: two five eight eleven fourteen
group2: seventeen twenty twentythree twentysix twentynine
group3: thirtytwo

Paste the following in Node 3's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group1: three six nine twelve fifteen
group2: eighteen twentyone twentyfour twentyseven thirty
group3: thirtythree

但我完全不知道该怎么做。我觉得可以在我的while循环里用嵌套的for循环来实现这个功能,但我一直没能得到想要的结果。我不确定自己是不是想太多了,或者我可能真的需要休息一下,哈哈。有没有什么建议可以帮帮我呢?

2 个回答

1

如果我理解你的问题没错的话,这其实就是把一堆东西分成几块简单的列表。你可以使用funcy这个库来实现:

>>> from funcy import chunks
>>> s = "one two three four five six seven eight nine ten eleven"
>>> databases = chunks(5, s.split())
>>> databases
[['one', 'two', 'three', 'four', 'five'], ['six', 'seven', 'eight', 'nine', 'ten'], ['eleven']]
>>> databases[0]
['one', 'two', 'three', 'four', 'five']
>>> databases[1]
['six', 'seven', 'eight', 'nine', 'ten']
>>> databases[2]
['eleven']
>>> len(databases[0])
5
>>> len(databases[1])
5
>>> len(databases[2])
1

你的代码可以这样重写:

#!/usr/bin/env python


from __future__ import print_function


from funcy import chunks


s = raw_input("Enter databases: ")

nodes = chunks(5, s.split())

for i, node in enumerate(nodes):
    print("Paste the following in Node 1's file")
    print("--------------------------------------------")
    print("[[INSTANCE]")
    print("#  Keep a blank space after the colon character.")
    print("#")
    print("group{0:d}:".format(i), end="")
    for db in node:
        print(" " + db, end="")

下面是一个示例输出:

$ python bar.py 
Enter databases: a b c d e f g h i j k l m n o p q r s t u v w x y z
Paste the following in Node 1's file
--------------------------------------------
[[INSTANCE]
#  Keep a blank space after the colon character.
#
group0: a b c d ePaste the following in Node 1's file
--------------------------------------------

还有其他类似的...

更新:

顺便说一下,你可以这样实现chunks功能:

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

这个方法是借鉴自:如何把列表分成大小相等的块?

1

如果你不想使用额外的模块,想要修正你代码的逻辑,那就把你的while循环部分改成下面这样。

i = 0
node1list = [[]]
node2list = [[]]
node3list = [[]]

while len(db_list) > 0:
    if len(node1list[i]) < 5:
        node1list[i].append(db_list.pop(0))
    elif len(node2list[i]) < 5:
        node2list[i].append(db_list.pop(0))
    elif len(node3list[i]) < 5:
        node3list[i].append(db_list.pop(0))
    else:
        node1list.append([])
        if len(db_list) > 5:
            node2list.append([])
            if len(db_list) > 10:
                node3list.append([])
        i += 1

撰写回答