如何创建具有可变数量 'for' 循环的函数,每个循环都有不同的索引?
How to create a function with a variable number of 'for' loops, each with a distinct index?
问题:
考虑一个 d 维的简单立方晶格。
如果点阵的宽度为L,则点阵点数为Ld.我想创建一个包含格点所有位置的列表,对于一般的 d 和 L.
例如,当 L = 2 和 d = 2 时,这将是 [(0, 0), (1, 0 ), (0, 1), (1, 1)].
我的尝试:
虽然我可以对一般 L 执行此操作,但我无法概括维度 d.
下面是我使用三个 for
循环对 d = 3 的解决方案。
def Positions(L):
PositionList = []
for i in range(L):
for j in range(L):
for k in range(L):
PositionList.append([k, j, i])
return PositionList
很容易看出我将如何改变它来增加或减少维度 d 因为我可以简单地添加或删除 for
循环,但显然它是为大 d.
写这个非常乏味
我考虑过使用递归 for
循环,所以我只会对任何 d 使用一个 for
循环,但我没有知道如何在保留索引的同时执行此操作我需要写出位置。
结论:
是否可以有可变数量的 for
循环,每个循环都有一个不同的索引来解决这个问题?
或者有没有不使用 for
循环的更好的解决方案?
递归确实是要走的路
想法是:
如果您假设您的函数适用于 d-1 维,那么您可以获取该结果并将 i
(循环变量)的值附加到每个结果,并为每个结果重复执行此操作i
.
的值
基本情况是 d=0 时,在这种情况下,您只有一个空结果。
编码方式如下:
def Positions(L, d):
if d == 0: # base case
return [[]]
return [
[i] + res # prepend i to the results coming from recursion
for i in range(L)
for res in Positions(L, d-1)
]
如果您不熟悉最终语句中使用的 list-comprehension 语法,那么在没有该语法的情况下您可以这样做:
def Positions(L, d):
if d == 0: # base case
return [[]]
positions = []
for i in range(L):
for res in Positions(L, d-1):
positions.append([i] + res)
return positions
你使用递归。第一部分是基本情况,第二部分是为较低维度的格子中的每个项添加从 0 到 L-1 的每个数字
def positions(L,d):
if d==0:
return [()]
else:
return [(x,)+positions(L,d-1)[y] for x in range(L) for y in range(len(positions(L,d-1)))]
一种简单的方法是使用 itertools
笛卡尔积:
from itertools import product
L, D = 2, 2
print(list(product(list(range(L)), repeat = D)))
Result
[(0, 0), (0, 1), (1, 0), (1, 1)]
问题:
考虑一个 d 维的简单立方晶格。
如果点阵的宽度为L,则点阵点数为Ld.我想创建一个包含格点所有位置的列表,对于一般的 d 和 L.
例如,当 L = 2 和 d = 2 时,这将是 [(0, 0), (1, 0 ), (0, 1), (1, 1)].
我的尝试:
虽然我可以对一般 L 执行此操作,但我无法概括维度 d.
下面是我使用三个 for
循环对 d = 3 的解决方案。
def Positions(L):
PositionList = []
for i in range(L):
for j in range(L):
for k in range(L):
PositionList.append([k, j, i])
return PositionList
很容易看出我将如何改变它来增加或减少维度 d 因为我可以简单地添加或删除 for
循环,但显然它是为大 d.
我考虑过使用递归 for
循环,所以我只会对任何 d 使用一个 for
循环,但我没有知道如何在保留索引的同时执行此操作我需要写出位置。
结论:
是否可以有可变数量的 for
循环,每个循环都有一个不同的索引来解决这个问题?
或者有没有不使用 for
循环的更好的解决方案?
递归确实是要走的路
想法是:
如果您假设您的函数适用于 d-1 维,那么您可以获取该结果并将 i
(循环变量)的值附加到每个结果,并为每个结果重复执行此操作i
.
基本情况是 d=0 时,在这种情况下,您只有一个空结果。
编码方式如下:
def Positions(L, d):
if d == 0: # base case
return [[]]
return [
[i] + res # prepend i to the results coming from recursion
for i in range(L)
for res in Positions(L, d-1)
]
如果您不熟悉最终语句中使用的 list-comprehension 语法,那么在没有该语法的情况下您可以这样做:
def Positions(L, d):
if d == 0: # base case
return [[]]
positions = []
for i in range(L):
for res in Positions(L, d-1):
positions.append([i] + res)
return positions
你使用递归。第一部分是基本情况,第二部分是为较低维度的格子中的每个项添加从 0 到 L-1 的每个数字
def positions(L,d):
if d==0:
return [()]
else:
return [(x,)+positions(L,d-1)[y] for x in range(L) for y in range(len(positions(L,d-1)))]
一种简单的方法是使用 itertools
笛卡尔积:
from itertools import product
L, D = 2, 2
print(list(product(list(range(L)), repeat = D)))
Result
[(0, 0), (0, 1), (1, 0), (1, 1)]