【问题标题】:Can I change variables outside of a for loop from within a for loop in python?我可以在python的for循环中更改for循环之外的变量吗?
【发布时间】:2020-02-05 04:23:03
【问题描述】:

我正在尝试编写一个程序来计算列表中某个项目大于其任一侧相邻邻居的次数:

inp = [1, 2, 3, 2, 8, 7, 6, 9, 5]

def check(n):
    count = 0
    ind_num1 = 0
    ind_num2 = 2
    index1 = n[ind_num1]
    index2 = n[ind_num2]
    for i in n[1:-1]:
        if i > index1 and i > index2:
            count += 1
        ind_num1 += 1
        ind_num2 += 1
    return count

print(check(inp))

我的解决方案是检查 for 循环 (i) 中的值是否大于其上方和下方的索引,同时每次通过循环为每个相邻索引添加一个。 ind_num1ind_num2 在循环进行时显示正确的值。但是,index1index2 保持不变,而不是随着 ind_num1 和 `ind_num2' 的值递增。他们为什么不改变?

【问题讨论】:

  • 我刚刚意识到 index1 和 index2 的值是 1 和 3,因为它们是列表中 0、2 的值。但同样的问题也适用于标题,为什么它们没有改变?
  • 您想将inp[0]inp[-1]inp[1] 进行比较吗?
  • No inp[0] 没有两个邻居,inp[-1] 也没有

标签: python loops for-loop variables variable-assignment


【解决方案1】:

ind_num1ind_num2 似乎对 index1index2 没有影响的原因是因为您在循环中递增前两个变量,但您已经分配了 index1 的值和index2 在循环之外。因此index1index2 将始终分别为02。如果要index1index2 准确反映ind_num1ind_num2 的值,则需要在循环的每次迭代中更新循环内的index1index2 的值。

inp = [1, 2, 3, 2, 8, 7, 6, 9, 5]

def check(n):
    count = 0
    ind_num1 = 0
    ind_num2 = 2
    for i in n[1:-1]:
        index1 = n[ind_num1]
        index2 = n[ind_num2]
        if i > index1 and i > index2:
            count += 1
        ind_num1 += 1
        ind_num2 += 1
    return count

print(check(inp))

如果您还想将列表中的第一项与最后一项和第二项进行比较,并将列表中的最后一项与倒数第二项和第一项进行比较,那么它就像...

inp = [1, 2, 3, 2, 8, 7, 6, 9, 5]

def check(n):
  count = 0
  for e,i in enumerate(inp):
    follIndex = e+1 if e+1 < len(n) else 0 # Changes index of following item to 0 if comparing last item in the list.
    if i > inp[e-1] and i > inp[follIndex]:
      count += 1
  return count

print(check(inp)) # Returns and prints '3' because three values (3, 8, 9)
                  # are bigger than both of the adjacent values in the list.

您可以通过枚举列表来跟踪当前索引,其中e 的值是一个整数,始终表示当前项的索引。

跟踪当前索引或e 的目的是让您可以通过inp[e-1]inp[e+1] 轻松访问相邻的列表项。

这可以让您摆脱许多不必要的变量。


由于您不想比较第一项或最后一项,因此您可以这样做:

inp = [1, 2, 3, 2, 8, 7, 6, 9, 5]

def check(n):
  count = 0
  for e,i in enumerate(n[1:-1]):
    if i > n[e] and i > n[e+2]:
      count += 1
  return count

print(check(inp))

您使用enumerate 将迭代(即01、...6)量化为e。该值(即e)用于确定相邻的列表项(即n[e] and n[e+2]),这使您可以摆脱所有那些不必要的变量。 FWIW,i 本质上等于e+1

【讨论】:

  • @Harry 我很确定您仍然可以将其标记为答案,因为我确实回答了您的问题以及所有...?
  • @Harry 参考我最后的评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 2017-09-30
相关资源
最近更新 更多