【问题标题】:How to make a for loop iterate together with the inside for loop both iterating on an array in python?如何使 for 循环与内部 for 循环一起在 python 中的数组上迭代?
【发布时间】:2019-09-23 15:52:15
【问题描述】:

我正在尝试制作一个可以通过字面计数来添加的程序。但为此,我有 2 个需要一起工作的 for 循环。例如,如果我输入 3 和 2,则外部 for 循环迭代到数组中的“3”,然后另一个 for 循环在数组上迭代直到“2”,这样外部 for 循环应该(但不) 对其进行迭代,并最终打印出它所在的位置(应该是 5)。我怎样才能做到这一点?因为现在内部循环将完成它的迭代并中断。

arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
#print(arr[0])
a = str(input()) #first number
b = str(input()) #second number

for i in arr:
    if i == a:
        for j in arr:
            if j == b:
                print(i)
                break

这个程序为输入 3 和 2 输出 3,但我想要 5

【问题讨论】:

  • 你能发布一个示例输出吗??
  • @abheet22 我想要的输出还是这段代码给出的输出?我希望它为 3 和 2 输出 5 但这输出 3
  • 所提到的输入你想要的输出。
  • 最简单的方法是让变量随着第一次和第二次循环的每次迭代而递增。
  • input 已经返回了 str 值;无需致电str

标签: python for-loop iteration counting


【解决方案1】:

您可以使用另一个变量来跟踪计数,如下所示:

arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

a = str(input())  # first number
b = str(input())  # second number

counter = 0
for i in arr:
    if i == a:
        for j in arr:
            if j == b:
                print(counter)
                break
            counter += 1
    counter += 1

我们可以编写一个程序来更简单地实现类似的行为:

a = int(input())  # first number
b = int(input())  # second number

counter = 0

for _ in range(a):
    counter += 1
for _ in range(b):
    counter += 1
print(counter)

这样做的好处是我们不限于arr 中的输入。

【讨论】:

  • 我想制作一个可以直接添加的程序,但如果我只是使用内置的添加,它会破坏目的,因为我可以简单地添加print(3 + 2)。我希望它只迭代数组以给出答案。
  • 请你想出一种不使用 + 运算符的方法,因为使用它来实现加法是自动的,我还想为它添加进位能力,而 + 本身就是这样做的。
【解决方案2】:

这是我的解决方案:

arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
num_list = list(range(int(arr[-1])*2+1))

new_dict = dict()
for index, value in enumerate(num_list):
    new_dict[value] = set()
    for item1 in arr:
        for item2 in arr:
            if int(value) == int(item1) + int(item2):
                new_dict[value].add((item1, item2))

a = str(input())  # first number
b = str(input())  # second number

target = (a, b)

for key, value in new_dict.items():
    if target in value:
        print(int(key))

希望对您有所帮助。如果您可以在不使用任何“+”的情况下实现目标,我很感兴趣。如果你找到了请分享。提前致谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多