【问题标题】:Using loop to go through range to select a single value each time使用循环遍历范围以每次选择一个值
【发布时间】:2018-08-16 11:57:50
【问题描述】:

我正在尝试创建一个 for 循环或列表理解,它可以遍历一个范围,每次通过按顺序移动每个索引来提取单个值,存储它,然后将其与另一个值进行比较。 例如:

def home():
    for i in range (1,10):
        ###not sure how to extract one by one
        ### take that single value that was extracted from the range above and 
        reduce  it from a index of type int
        t_1 = (board[0] - i )
        ### call upon a function and plug in result:
        reducer(t_1)
        if reducer is True:
             print ('hello world')
        else:
            home()

所以基本上函数 home() 在循环中运行,直到它在范围内找到正确的数字,将其作为参数插入到函数 reducer(t_1) 并返回结果。 问题是我无法理解如何创建第一个 for 循环或列表理解以从所需范围中一次提取一个值,存储它然后对其进行评估。

【问题讨论】:

  • t_all = [board[0]-i for i in range(1,10)] 怎么样。现在,t_all 将包含所有 t_1s,然后您可以将此列表发送到 reducer
  • if reducer is True - reducer 是一个函数,所以它的真值总是True。您的意思是 if reducer(t_1):... 以便评估 reducer 返回的值吗? (旁注:在if 语句中,if 后面的表达式总是被评估为布尔值 - True 或 False - 所以附加 is Trueis False 是多余的。if x:if not x: 就足够了)。

标签: python list for-loop list-comprehension


【解决方案1】:

我从你的问题中了解到,这就是我假设的意思:

t_all = [board[0]-i for i in range(1,10)]

使用列表推导,您循环 1 到 10,然后从 board[0] 中减去每个值,并将它们全部存储在一个列表中。然后,您可以将列表传递给您的函数。

【讨论】:

  • 我想从 board [0] 中减去 t_all 中的所有值,但一次一个。不是一下子。例如:
  • 但这就是您已经在代码中执行的操作。那有什么问题呢?要将home()的函数调用放入for循环吗?
猜你喜欢
  • 2022-08-17
  • 1970-01-01
  • 2010-11-30
  • 2015-01-07
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
相关资源
最近更新 更多