【问题标题】:How to check if the condition is true at least once in Python?如何在 Python 中至少检查一次条件是否为真?
【发布时间】:2020-03-11 03:46:15
【问题描述】:

假设我有几个列表。如果数字 1 至少出现一次,我想将其返回为 True。如果没有出现 1 的实例,则为 False。所以假设我有几个列表。

[2.0,2.0]
[1.0, 1.0, 2.0, 2.0]
[1.0, 2.0]
[3.0, 1.0]
[3.0, 3.0, 1.0, 1.0]
[3.0, 3.0, 3.0, 3.0]

输出将是:

False
True
True
True
True
False

我怎样才能做到这一点?

编辑:代码示例

def is_walkable(i,j,current_board):
    # find all the diagonal neighbours of (i,j) that are on board and put them into a list
    diagonal_neighbors = [(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)]
    # loop over the list of neighbours to see if any of them is empty 
    neighbor_values = []
    for neighbor in diagonal_neighbors:
        row = neighbor[0]
        col = neighbor[1]
    # if there is an empty neighbour, return True, otherwise return False
        if on_board(row,col,current_board):
            neighbor_values.append(current_board[row,col])
        for neighbor in neighbor_values:
            if any(neighbor_values) == 1:
                return True
            else:
                return False

测试代码是:

current_board = initial_board(empty_board)
print(is_walkable(0,1,current_board) == False)
print(is_walkable(2,1,current_board) == True)
print(is_walkable(2,7,current_board) == True)
print(is_walkable(5,0,current_board) == True)
print(is_walkable(5,6,current_board) == True)
print(is_walkable(6,1,current_board) == False)

所有输出都应该是“真”。这是一个 8x8 棋盘上的跳棋游戏。

【问题讨论】:

  • ['1' in a_list for a_list in list_of_lists]
  • 您说“所有输出都应为True”,但您的代码显示您为某些输出打印== False,为其他输出打印== True。您究竟要在这里测试什么 - 预期结果是什么,而您得到的结果是什么?
  • 测试代码已提供给我。我没有输入它,我知道它不是很直观,但以前也有类似的东西。本质上,如果函数的正确输出为 false,我们将其设置为 == false,则输出为 true。
  • 我的结果显示为 False True True True True False,但应该显示为 True True True True True True True。如果需要,我可以发送整个笔记本。

标签: python list loops any


【解决方案1】:

我想这就是你所追求的:

xss = [
    [2.0, 2.0],
    [1.0, 1.0, 2.0, 2.0],
    [1.0, 2.0],
    [3.0, 1.0],
    [3.0, 3.0, 1.0, 1.0],
    [3.0, 3.0, 3.0, 3.0],
]

print(any(1.0 in xs for xs in xss))

any 将导致生成器1.0 in xs for xs in xss 继续检查xss 中的列表,直到其中一个包含1.01.0 in xs

如果您想完全理解解决方案,请查看any 以及生成器和推导式的文档,但我认为解决方案本身很清晰且易于理解。

如果您只想要列表的布尔值列表:

has_one_xss = [1.0 in xs for xs in xss]

print(has_one_xss)

打印:

[False, True, True, True, True, False]

【讨论】:

  • 谢谢!但是,这些列表不包含在列表中。这些列表彼此独立。我怎么一次做这个?因此,如果我只看 [2.0,2.0] 本身,如何将其设置为 false?
  • 请用实际的代码示例更新您的问题,这样我就不必猜测您的列表在哪里以及您的变量被称为什么。
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2017-10-06
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多