Python 求助一个算法问题

flyfire · 2019年07月19日 · 最后由 flyfire 回复于 2019年07月24日 · 2348 次阅读

有一个字符串,字符串中包含三个变量,而三个变量,每个变量又有多个取值,怎么全遍历一遍?
比如
str1 = "第一个变量{var1},第二个变量{var2},第三个变量{var3}"
var1=["1","2","3"]
var2=["4","5","6","7"]
var3=["8","9","10"]

str1 的遍历应该有 3*4*3 种结果

请问怎么简单点搞出来结果?

共收到 6 条回复 时间 点赞

var1=["1","2","3"]
var2=["4","5","6","7"]
var3=["8","9","10"]
s = ((x,y,z) for x in var1 for y in var2 for z in var3)
count = 0
for i in s:
count+=1
print(i)
print(count)

for n in (var1+var2+var3) :
print n

arrow 回复

还是你的方法最好了

arrow 回复
import copy

a=["1","2","3"]
b=["4","5","6","7"]
c=["10","8","9"]


def insert( sum, values ):
    if sum == []:
        for value in values:
            sum.append( [value] )
        return
    tmp = copy.deepcopy(sum) 
    for item in tmp:
        for value in values:
            sum.append( item + [value] )
        sum.remove( item )


if __name__ == "__main__":
    sum = []        
    for values in [a,b,c]:
        insert( sum, values )
    for i in sum:
        print(i)

结果:
['1', '4', '10']
['1', '4', '8']
['1', '4', '9']
['1', '5', '10']
['1', '5', '8']
['1', '5', '9']
['1', '6', '10']
['1', '6', '8']
['1', '6', '9']
['1', '7', '10']
['1', '7', '8']
['1', '7', '9']
['2', '4', '10']
['2', '4', '8']
['2', '4', '9']
['2', '5', '10']
['2', '5', '8']
['2', '5', '9']
['2', '6', '10']
['2', '6', '8']
['2', '6', '9']
['2', '7', '10']
['2', '7', '8']
['2', '7', '9']
['3', '4', '10']
['3', '4', '8']
['3', '4', '9']
['3', '5', '10']
['3', '5', '8']
['3', '5', '9']
['3', '6', '10']
['3', '6', '8']
['3', '6', '9']
['3', '7', '10']
['3', '7', '8']
['3', '7', '9']

当时我是这么写的,感觉很不 pythonic

哈哈哈,又学到一招

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册