简体   繁体   English

如何在游戏(列表)中找到元素的位置?

[英]How to find position of elements in a game (list)?

In this game, there is only one element at the position (0, 0) represented by 'o'.在这个游戏中,位置 (0, 0) 只有一个元素,用 'o' 表示。 The rest are occupied.其余的都被占用了。 Write a function empty(game) that takes in a game and gives the list of the positions of all empty spaces.编写一个函数 empty(game) ,它接受一个游戏并给出所有空白空间的位置列表。 Each position is specified by an (i,j) .每个位置由(i,j)指定。 For example,例如,

game =  [['o', 'x', 'x'],
         ['x', 'x', 'x'],
         ['x', 'x', 'x']]

empty(game) gives [(0,0)]空(游戏)给出 [(0,0)]


def empty_spaces(game):
    result = [0]
    num_of_rows = len(game)
    num_of_columns = len(game[0])
    for i in range(num_of_columns):
        for j in range(num_of_rows):
            if not "o":
                result += i[j]
    return result

However, the result I get is [0] .但是,我得到的结果是[0] I would appreciate some help and thank you very much!我将不胜感激,非常感谢您的帮助!

You have iterate over the game list and see if you find 'o' if there's a hit then append that elements co-ordinates to result .您已经遍历了game列表,看看是否找到'o'是否有命中,然后将该元素坐标附加到result The errors in your I would like to point out are if not "o" is always true, result=[0] you wouldn't want to do it.我想指出的错误是if not "o"总是正确的,则result=[0]你不会想要这样做。 Instead simply write result= [] or result= list() .而是简单地写result= []result= list() result+= i[j] i in your code is not iterable it is a integer. result+= i[j] i在您的代码中是不可迭代的,它是一个整数。 Since we checking if every element is equal to "o" the time complexity is O(rows*columns) .由于我们检查每个元素是否等于"o"因此时间复杂度为O(rows*columns)

game =  [['o', 'o', 'x'],
         ['x', 'x', 'x'],
         ['x', 'x', 'o']]
result=[]
for i in range(len(game)):
    for j in range(len(game[i])):
        if game[i][j] == 'o':
            result.append((i,j))
print(result)

>>> [(0, 0), (0, 1), (2, 2)]

Something like this should work:这样的事情应该工作:

game =  [['x', 'x', 'o'],
         ['x', 'o', 'x'],
         ['x', 'x', 'o']]

def empty_spaces(board):
    result = []

    for r_index, row in enumerate(board):
        for c_index, column in enumerate(row):
            if 'o' in column:
                result.append((r_index, c_index))

    return result

print(empty_spaces)

>>> [(0, 2), (1, 1), (2, 2)]

The problem is with the statement if not 'o': .问题在于语句if not 'o':

For us humans it's obvious, within the context of the program, that we want to check whether or not the element at index (i, j) is the string 'o' .对于我们人类来说,很明显,在程序的上下文中,我们想要检查索引 (i, j) 处的元素是否是字符串'o'

Unfortunately, the nature and limitations of Python mean that we must be explicit and specific: if game[i][j] == 'o': .不幸的是,Python 的本质和局限性意味着我们必须明确且具体: if game[i][j] == 'o':

This particular mistake is quite annoying since, despite the fact that part of the expression is missing, the code runs perfectly fine, because of something called truthyness.这个特殊的错误非常令人讨厌,因为尽管缺少部分表达式,但由于称为真实性的东西,代码运行得非常好。 Truthyness (and its counterpart, falsyness), is the idea that something which isn't a boolean can be converted to/evaluated as one.真实性(及其对应的虚假性)是指可以将不是布尔值的事物转换为/评估为一个的想法。 In the case of Python strings, empty strings are falsy (they evaluate to False) nonempty strings are truthy (you get it).在 Python 字符串的情况下,空字符串是假的(它们评估为 False)非空字符串是真的(你明白了)。 The if statement in your code is therefore evaluated like so: if not 'o': —> if not True: —> if False: .因此,代码中的 if 语句的计算方式如下: if not 'o': —> if not True: —> if False: As you can tell, the contents of that if statement would never be executed.如您所知,该 if 语句的内容永远不会被执行。


Here is how I would rewrite your code:以下是我将如何重写您的代码:

game =  [['o', 'x', 'x'],
         ['x', 'x', 'x'],
         ['x', 'o', 'x']]


def empty_indexes(board):
    index_list = []
    for row_idx, row in enumerate(board):
        for col_idx, elem in enumerate(row):
            if elem == 'o': 
                index_list.append((row_idx, col_idx))
    return index_list

enumerate() is a simple and extremely useful function which returns pairs composed of one of the elements in the input, and a counter, which is incremented each time. enumerate()是一个简单且非常有用的函数,它返回由输入中的一个元素和一个每次递增的计数器组成的对。 When used on a list, like in the code above, it returns what corresponds to (index, element) pairs.当在列表上使用时,就像上面的代码一样,它返回对应于 (index, element) 对的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM