【问题标题】:How to generalize this for loop for any lenght?如何将这个 for 循环概括为任何长度?
【发布时间】:2021-04-21 20:49:31
【问题描述】:

我想在 python 中对任何“pos”长度进行概括

for a in range(pos[0]):
    for b in range(pos[1]):
        for c in range(pos[2]):
            for d in range(pos[3]):
                for e in range(pos[4]):
                    for f in range(pos[5]):     
                        neighbours.append([a, b, c, d, e, f])

我想在 6 个维度上收集我位置的所有邻居。邻居是所有坐标的x-1xx+1 的所有组合。所以我必须收集 3^dim -1 个邻居。 pos 是一个 {dim} 长度列表,其中包含所有坐标的位置。 dx 是离散化长度。正如您所看到的,所有循环都是相同的,除了pos 中的索引增加,所以如果可能的话,我想概括一下。

for a in range(pos[0]- self.dx, pos[0]+2*self.dx, self.dx):
    for b in range(pos[1]- self.dx, pos[1]+2*self.dx, self.dx):
        for c in range(pos[2]- self.dx, pos[2]+2*self.dx, self.dx):
            for d in range(pos[3]- self.dx, pos[3]+2*self.dx, self.dx):
                for e in range(pos[4]- self.dx, pos[4]+2*self.dx, self.dx):
                    for f in range(pos[5]- self.dx, pos[5]+2*self.dx, self.dx):     
                        neighbours.append([a, b, c, d, e, f])

【问题讨论】:

  • for item in pos:
  • 查找intertools 包,特别是应用于项目列表的product 方法。语法类似于neighbours = list(product(pos*))
  • 错字:itertools

标签: python python-3.x for-loop


【解决方案1】:

您可以使用递归轻松解决它:

def combinations(pos, acc=[[]] * 3):
    if len(pos) == 0:
        return a    Cloud

    Amazon announced a $250 million venture fund to invest in Indian startups cc
    else:
        return combinations(pos[1:],
                            acc = \
                            [x + [y] for x in acc for y in pos[0]])

测试它:

combinations([['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h']])

这给出了:

[['a', 'd', 'f'],
 ['a', 'd', 'g'],
 ['a', 'd', 'h'],
 ['a', 'e', 'f'],
 ['a', 'e', 'g'],
 ['a', 'e', 'h'],
 ['b', 'd', 'f'],
 ['b', 'd', 'g'],
 ...
  ['a', 'd', 'f'],
 ['a', 'd', 'g'],
 ['a', 'd', 'h'],
 ['a', 'e', 'f'],
 ['a', 'e', 'g'],
 ['a', 'e', 'h'],
 ['b', 'd', 'f'],
 ['b', 'd', 'g'],
 ['b', 'd', 'h'],
 ['b', 'e', 'f'],
 ['b', 'e', 'g'],
 ['b', 'e', 'h'],
 ['c', 'd', 'f'],
 ['c', 'd', 'g'],
 ['c', 'd', 'h'],
 ['c', 'e', 'f'],
 ['c', 'e', 'g'],
 ['c', 'e', 'h']]

要删除重复项,请在结果周围加上list(set()),或者如果您想保持顺序:

result_list_unique = []
for x in result_list:
    if x not in result_list_unique:
        result_list_unique.append(x)

并使用result_list_unique

【讨论】:

  • 好的,我试过了,效果很好,除了它还会多次返回一些组合。感谢您的帮助
  • 在这种情况下,只需在结果周围加上list(set()) - 使其独一无二
  • 如果对你有帮助,请选择它作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2022-12-08
  • 2016-03-10
相关资源
最近更新 更多