【问题标题】:Python function to return list of lists by only swapping the same indicesPython函数通过仅交换相同的索引来返回列表列表
【发布时间】:2021-01-17 23:31:14
【问题描述】:

我有两个包含 5 个元素的列表。我想使用 itertools 或 python 代码返回一个包含 5 个元素的列表,该列表由列表的所有排列组成,仅交换具有相同索引的两个列表的元素。

例如,如果A = [1,2,3,4,5]B = [a,b,c,d,e],我希望它返回以下列表列表,C:

A 中没有元素被B 替换的情况:

[1,2,3,4,5]

A 中的所有索引都被 B 替换的情况:

[a,b,c,d,e]

A 中只有一个元素被 B 中具有匹配索引的元素替换的情况:

[a, 2, 3, 4, 5]
[1, b, 3, 4, 5]
[1, 2, c, 4, 5]
[1, 2, 3, d, 5]
[1, 2, 3, 4, e]

A 中的两个元素被B 中具有匹配索引的元素替换的情况(注意:这可以是任意两个元素,两个元素不必相邻):

[a, b, 3, 4, 5]

[1, b, c, 4, 5]

[1, 2, c, d, 5] …等等…

[a, 2, 3, 4, e]

[1, b, 3, c, 5] …等等…

替换 3 个元素的情况(同样,这可以是任意 3 个元素):

[a, b, c, 4, 5]

[1, b, c, d, 5] …等等…

替换4个元素的情况(任意4个元素):

[a, b, c, d, 5]

[a, 2, c, d, e]

[a, b, c, 4, e] ...等...

我认为使用 itertools 会很简单,但在创建此列表时遇到了问题。

【问题讨论】:

  • 你确定你的意思是 permutations 吗?因为在您的示例中,列表元素的 order 永远不会改变!

标签: python list combinations permutation itertools


【解决方案1】:

这是一个单一的班轮:

from itertools import product

A = [1,2,3,4,5]
B = ['a','b','c','d','e']
n = len(A)

out = [[(A if x[i] else B)[i] for i in range(n)] for x in product([0,1], repeat=n)]

或者(稍微)更pythonic:

out = [[(A if y else B)[i] for i,y in enumerate(x)] for x in product([0,1], repeat=n)]

说明: x 涵盖了在 AB 中选择 i'th 元素的所有可能性。

如果这对你来说太神秘了,那么这里是扩展版本:

out = []
for x in product([0,1], repeat=n):
    l = []
    for i in range(n):
        if x[i]:
            l.append(A[i])
        else:
            l.append(B[i])
    out.append(l)

【讨论】:

  • 酷。但是对于初学者来说,单线可能太dense....(一个简单的for循环可以提供帮助吗?)
  • 添加了多线版本:)
  • 谢谢,TIL。喜欢单线更好... ;-)
【解决方案2】:

如果我采用您的 examples 并忽略单词 permuations,那么您想要的是一个执行以下操作的迭代器:给定两个长度相等的列表作为输入,它返回一堆列表,其中第一个列表的元素被第二个列表的对应元素替换;并且要替换的元素的索引是所有可能索引的长度-N 组合

可能是带有生成器函数或迭代器类的东西...

def get_list_replacement_combinations(list_a, list_b):
  # skipping some checks, like lists having same length
  N = len(list_a)
  for num_replaced_items in range(N+1):
    new_list = list(list_a) # make a copy so we don't mess up the original
    for combination in itertools.combinations(range(N), r=num_replaced_items):
      for index in combination:
        new_list[index] = list_b[index]
      yield new_list

我是即时制作的,没有对其进行测试,因此可能存在错误,但这绝对是一般的想法。可能会弄乱替换项目的“长度 0”情况...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2013-02-25
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多