我有下面的代码,我想让它响应传递给它的初始数组(字母)。目前它可以处理字母<;=3,但是我想让它可以扩展到n
在本例中,如果数组只包含两个条目[“a”,“b”],它将触发第二个if语句。你知道吗
我怎样才能改变它,使它具有无限的if语句,允许一个任意大小的数组?你知道吗
import itertools
import numpy as np
#variable length
letters = ["a", " b", " c"]
increment = .1
d = 3
e = 3
#Calculate total possible combinations and create array
x=0
for p in itertools.product(range(d), repeat=e):
x = x+1
variable = np.arange(x)
variable_s = [str(x) for x in variable]
x=0
#run loop based on array length.
for p in itertools.product(range(d), repeat=e):
if len(letters) == 1:
variable_s[x] = letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "")
elif len(letters) == 2:
variable_s[x] = (
letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "")
+letters[1]+str(format(p[1]/(increment)**(-1.0),'.2f')).replace("0.", "")
)
elif len(letters) == 3:
variable_s[x] = (
letters[0]+str(format(p[0]/(increment)**(-1.0),'.2f')).replace("0.", "")
+letters[1]+str(format(p[1]/(increment)**(-1.0),'.2f')).replace("0.", "")
+letters[2]+str(format(p[2]/(increment)**(-1.0),'.2f')).replace("0.", "")
)
x = x+1
variable_s
上述代码的输出为: ['a00 b00 c00', 'a00 b00 c10', 'a00 b00 c20', 'a00 b10 c00', 'a00 b10 c10', 'a00 b10 c20', 'a00 b20 c00', 'a00 b20 c10', 'a00 b20 c20', ‘a10 b00 c00’, ‘a10 b00 c10’, ‘a10 b00 c20’, ‘a10 b10 c00’, ‘a10 b10 c10’, ‘a10 b10 c20’, ‘a10 b20 c00’, ‘a10 b20 c10’, ‘a10 b20 c20’, ‘a20 b00 c00’, ‘a20 b00 c10’, ‘a20 b00 c20’, ‘a20 b10 c00’, ‘a20 b10 c10’, ‘a20 b10 c20’, ‘a20 b20 c00’, ‘a20 b20 c10’, 'a20 b20 c20']
如果字母=[“a”,“b”],则输出为: ['a00 b00', 'a00 b00', 'a00 b00', 'a00 b10', 'a00 b10', 'a00 b10', 'a00 b20', 'a00 b20', 'a00 b20', ‘a10 b00’, ‘a10 b00’, ‘a10 b00’, ‘a10 b10’, ‘a10 b10’, ‘a10 b10’, ‘a10 b20’, ‘a10 b20’, ‘a10 b20’, ‘a20 b00’, ‘a20 b00’, ‘a20 b00’, “a20 b10”, “a20 b10”, “a20 b10”, “a20 b20”, “a20 b20”, 'a20 b20']
如果字母[“a”,“b”,“c”,“d”,“e”,“f”,“g”],则输出为: [“a00 b00 c00 d00 e00 f00 g00”, 'a00 b00 c00 d00 e00 f00 g10',。。。等等
下面是您可以做的最小更改—将
if
语句替换为:其他注意事项:
p[1]/(increment)**(-1.0)
拼写更好p[1] * increment
x=0; for p in itertools.product(range(d), repeat=e): x = x+1
拼写更好x = d**e
也许可以试试这样的?你知道吗
相关问题 更多 >
编程相关推荐