python - 如何压缩多个 for 语句,以便用户可以更改它们的数量
问题描述
我有一个代码,它可以获取每个数字组合(1 到 4),将它们加起来会得到你插入的数字(在这种情况下是 n)......
它基本上以 n 位列出数字 1、2、3 和 4 的每个组合,并添加了 if 语句以排除我在另一个程序中需要的那些。
我现在设置它的方式是将其锁定为 6 位,因为我必须手动更改 for 语句的数量才能更改。我的问题是如何制作它,以便我可以在控制台中输入尽可能多的 for 语句。
这是我的代码:
def num_of_comb(n):
counter = 0
for a in range(1, 5):
if a == n:
print(str(a))
counter += 1
for b in range(1, 5):
if a+b == n:
print(str(a) + str(b))
counter += 1
for c in range(1, 5):
if a+b+c == n:
print(str(a) + str(b) + str(c))
counter += 1
for d in range(1, 5):
if a+b+c+d == n:
print(str(a) + str(b) + str(c) + str(d))
counter += 1
for e in range(1, 5):
if a+b+c+d+e == n:
print(str(a) + str(b) + str(c) + str(d) + str(e))
counter += 1
for f in range(1, 5):
if a+b+c+d+e+f == n:
print(str(a) + str(b) + str(c) + str(d) + str(e) + str(f))
counter += 1
return counter
print(num_of_comb(int(input("Unesi broj: "))))
只有当我输入 6 时,此代码的结果才会正确,因为有 6 个 for 语句。
解决方案
我会去itertools.product
替换嵌套for
循环。
from itertools import product
numberOfLoops = int(input("Number of loops?"))
for t in product(range(1, 5), repeat=numberOfLoops):
# t is a tuple with all loops variables in it
if sum(t) == n:
# do stuff
您可以在此处阅读文档。
请注意,对于您要达到的特定目的,可能还有其他有趣的选项,例如itertools.combinations
.
推荐阅读
- android - Flutter - 如何使 DatePicker 中的选定值出现在 TextFormField 中?
- flutter - 本地化 jitsi_meet_flutter
- python - 熊猫四舍五入到最近的第一个月
- java - Spring Boot Client 调用由 OAuth2 保护的 REST API
- javascript - 使用 jQuery ajax 调用在 MVC 视图中绑定部分视图
- java - 使用 GrandID API 登录银行 ID - 瑞典
- sql - SQL Left Join 先匹配
- javascript - 如何避免访问远程服务器时请求的资源上不存在“Access-Control-Allow-Origin”标头
- python - 将文件作为输入从一个 python 传递到另一个
- python - 自定义活动正则化器以使用拉普拉斯算子平滑输出