我是Python的新手,我已经创建了一个函数,它接受整数列表(l)并打印这些整数的所有变体,如下所示:
def answer(l):
for i in range(0, len(l)+1):
for y in itertools.permutations(l, i):
s = str(y).replace(',', '')
p = s.replace(' ', '')
answer([3,3,7])
返回:
() (3) (3) (7) (33) (37) (33) (37) (73) (73) (337) (373) (337) (373) (733)
如何使用x%3 = 0找出哪些值可被3整除?
答案 0 :(得分:1)
右。你想要像
这样的东西if y % 3 == 0:
# whatever you want to do with those numbers.
如果你想在列表中使用它们,你可以使用理解:
tri = [x if x%3 == 0 for x in itertools.permutations(l, i)]
对OP评论的回应
"那么我现在如何在p变量中访问这些字符串值以确定它们是否可以被3整除?"
你不知道:字符串不能被整数整除。我希望您想要的是将数字部分转换为整数并测试 。
取 p 值,跳过括号,然后转换。我将代码分成更小的步骤;你可以在看到这个过程后将它结合起来:
for y in itertools.permutations(l, i):
s = str(y).replace(',', '')
p = s.replace(' ', '')
num_str = p[1:-1]
if len(num_str) > 0:
value = int(num_str)
if value % 3 == 0:
print value, "is divisible by 3"
else:
print value, "does not have trinary nature"
else:
print p, "empty number"
输出:
() empty number
3 is divisible by 3
3 is divisible by 3
7 does not have trinary nature
33 is divisible by 3
37 does not have trinary nature
33 is divisible by 3
37 does not have trinary nature
73 does not have trinary nature
73 does not have trinary nature
337 does not have trinary nature
373 does not have trinary nature
337 does not have trinary nature
373 does not have trinary nature
733 does not have trinary nature
733 does not have trinary nature