python 如何将项目从一个列表移动到另一个列表?

How to move Items from one list to the another list in python?

我想探索 10 个节点的每一种可能的社区分配。我总共有 10 个项目:10 15 25 30 45 50 65 75 80 90 有两个列表(社区)c1c2 我将分配这些项目。最初,我将 10 个项目拆分如下:

c1 = [10, 45, 50, 75, 90] c2 = [15, 25, 30, 65, 80]

现在我想将一个项目移动到另一个列表,例如:

c1 = [45, 50, 75, 90] c2 = [10, 15, 25, 30, 65, 80]
c1 = [10, 45, 50, 75] c2 = [15, 25, 30, 65, 80, 90]
...

我也想搬两件,三件,四件,(但不是五件)。喜欢,

c1 = [50, 75, 90] c2 = [10, 15, 25, 30, 45, 65, 80]
c1 = [10, 75, 90] c2 = [15, 25, 30, 45, 50, 65, 80]
...
c1 = [75, 90] c2 = [10, 15, 25, 30, 45, 50, 65, 80]
c1 = [10, 90] c2 = [15, 25, 30, 45, 50, 65, 75, 80]
...
c1 = [90] c2 = [10, 15, 25, 30, 45, 50, 65, 75, 80]
c1 = [45] c2 = [10, 15, 25, 30, 50, 65, 75, 80, 90]
...

我想将 1-4 项的所有可能迭代从 c1 移动到 c2。 (总共 31 种可能性:2^5-1)每个列表中的顺序无关紧要。我该怎么做?

我使用了下面的代码。

c1 = [10, 45, 50, 75, 90]
c2 = [15, 25, 30, 65, 80]

for i in c1:
    c2.append(i)
    c1.remove(i)
    print c1, c2 

使用这段代码,我只能得到以下结果。此代码未完成将一项移动到 c2 的任务。我的代码没有尝试将多个项目移动到 c2.

[45, 50, 75, 90] [15, 25, 30, 65, 80, 10]
[45, 75, 90] [15, 25, 30, 65, 80, 10, 50]
[45, 75] [15, 25, 30, 65, 80, 10, 50, 90]

如何才能顺利完成将物品移动到c2的任务?通过此任务,我可以将 10 个项目的所有可能分配到两个列表(忽略大小写 c1==c2)。

尝试:

c1.append(c2.pop(i))
c1.sort()

c2.append(c1.pop(i))
c2.sort()

其中:

  • i - 索引列表

如果您想创建 10 个项目到 2 个列表的所有可能分配,那么我会使用 itertools 包中的组合。例如:

import itertools
items = [10, 25, 45, 50, 15, 30, 65, 75, 80, 90]

for m in xrange(len(items)+1):
    combinations = list(itertools.combinations(items, m))
    for c1 in combinations:
       c1 = list(c1)
       c2 = list(set(items) - set(c1))
       print c1, c2

据我了解,您对算法更感兴趣,而不是简单地从一个列表追加到另一个列表。

有一个标准库函数提供 iterable.

的组合

制作自己的combinations函数真是一个很好的练习。

您问题的快速粗略解决方案:

import itertools

c1 = [10, 45, 50, 75, 90]
c2 = [15, 25, 30, 65, 80]

print c1, c2
for i in range(1, 5):
    for c in itertools.combinations(c1, i):
        mc1 = sorted(list(set(c1).difference(set(c))))
        mc2 = sorted(list(set(c2).union(c)))
        print mc1, mc2

以下将项目从一个列表移动到另一个列表,而不会出现您在原始问题中遇到的不正确的迭代器位置问题:

c1 = [10, 45, 50, 75, 90]
c2 = [15, 25, 30, 65, 80]

while c1:
    c2.append(c1[0])
    del c1[0]
    print (c1, c2)