Python无法比较字符串 [英] Python fails to compare strings

查看:139
本文介绍了Python无法比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中遇到了一个奇怪的问题。我有一个迷宫,x代表墙壁,g是目标,s是起点,数字是将您从一个数字带到另一个数字的门户(例如,如果您使用2的一个,它将把您带到其他2)。

I'm facing a strange problem in python. I have a maze, x's stand for walls, g is a goal, s is the starting point and the numbers are portals which bring you from one number to the other (e.g. if you go on one of the 2's it will transport you to the other 2).

xxxxxxxxxxxxxxxxxxxx
x2                 x
x       xxx        x
x   1   x xxxxx    x
x   s     x        x
x       x x  xxxxxxx
x  xx xxxxx        x
x      x      g    x
x   1  x  2        x
xxxxxxxxxxxxxxxxxxxx

我正在尝试查找所有门户并将它们放入数组中。到目前为止,该程序有效,该程序找到了所有四个门户。

I'm trying to find all portals and put them into an array. So far this works, the program finds all four portals.

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
file = filedialog.askopenfilename()

def readMazeToArray(path):
    with open(path) as f:
        return [list(line.strip()) for line in f]

maze = readMazeToArray(file)

def findPortals(maze):
    portals = []
    for i in range(0, len(maze)):
        for j in range(0, len(maze[i])):
            if (maze[i][j] != 'g' and maze[i][j] != 's' 
            and maze[i][j] != 'x' and maze[i][j] != ' '):
                portals.append([i, j])
    return portals

从那时起,事情变得有些奇怪。以下代码似乎无法正常工作:

And from then on things are getting a bit strange. Here's the code that doesn't seem to work right:

def portalHeuristic(maze, x1, x2, y1, y2):
    portals = findPortals(maze)
    for portal in portals:
        for i in range(0, len(maze)):
            for j in range(0, len(maze[i])):

                if maze[i][j] == maze[portal[0]][portal[1]] 
                and (portal[0] != i or portal[1] != j):

                     return abs(x1 - portal[0]) + abs(y1 - portal[1]) 
                            + abs(x2 - i) + abs(y2 - j))

        print(maze[i][j] == maze[portal[0]][portal[1]])

        print("x1 = ", x1, ", y1 = ", y1, ", portal0 = ", 
        portal[0], ", portal1 = ", portal[1], ", x2 = ",
        x2, ", y2 = ", y2, ", i = ",  i, ", j = ", j)


portalHeuristic(maze, 4, 4, 7, 14)

portalHeuristic 的基本用途是现在在另一个之后,通过一个门户进行迭代er寻找当前门户网站的相同符号( maze [i] [j] == maze [portal [0]] [portal [1]] ),但确保它没有通过比较当前门户和找到的具有相同符号/数字的门户的坐标来找到当前门户本身( portal [0]!= i或portal [1]!= j )。最终,它会计算起点和当前门户之间的距离,以及它的双门户与目标之间的距离。

What portalHeuristic basically does is it now iterates through one portal after another looking for the same symbol (maze[i][j] == maze[portal[0]][portal[1]]) of the current portal but ensures that it didn't find the current portal itself by comparing the coordinates of the current portal and the portal it has found with the same symbol/ number (portal[0] != i or portal[1] != j). Eventually it computes the distance between starting point and current portal and its twin portal and the goal.

但是好像 maze [i] [j ] == maze [portal [0]] [portal [1]] 似乎不起作用,因为我的程序总是告诉我在i = 9,j = 19处找到了另一个门户,否哪个门户网站无关紧要。奇怪的是,如果我在自己的python上测试字符串的相等性,就会意识到它总是错误的。我究竟做错了什么?我现在已经花了3个多小时来寻找错误,但似乎找不到它。也许这是一个非常愚蠢的人?
另外,请忍受我糟糕的代码。我刚开始使用python。

But it seems like maze[i][j] == maze[portal[0]][portal[1]] doesn't seem to work since my program always tells me the other portal was found at i=9, j=19, no matter which portal. Strangely enough if I test for the equality of the strings on its own python realizes that it is always false. What am I doing wrong? I've now spent more than 3 hours looking for the error, but I can't seem to find it. Maybe it's a really stupid one? Also, please bear with my terrible code. I just started with python.

推荐答案

很难为写出一旦您熟悉列表理解就循环播放

its hard to write out for loops once you're familliar with list comprehensions

,但也许您可以使用> http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

我在listcomps中添加了换行符和空格,以增强可读性

I added line breaks and leading whitespace inside the listcomps in an atempt to help readability

您还应该看到枚举在这些类型的索引循环上对元素进行测试非常有用

you should also see that enumerate is very helpful in these types of indexing loops with test on elements

maze = ['xxxxxxxxxxxxxxxxxxxx',
 'x2                 x',
 'x       xxx        x',
 'x   1   x xxxxx    x',
 'x   s     x        x',
 'x       x x  xxxxxxx',
 'x  xx xxxxx        x',
 'x      x      g    x',
 'x   1  x  2        x',
 'xxxxxxxxxxxxxxxxxxxx']

prtls = [[c, (j, k)]
         for k, ln in enumerate(maze)
            for j, c in enumerate(ln) if c.isdigit()]
prtls
Out[206]: [['2', (1, 1)], ['1', (4, 3)], ['1', (4, 8)], ['2', (10, 8)]]

grpd_prtls = [[n, [p[1]
               for p in prtls if p[0] == n]]
              for n in sorted(set(p[0] for p in prtls))]
grpd_prtls
Out[207]: [['1', [(4, 3), (4, 8)]], ['2', [(1, 1), (10, 8)]]]

grpd_prtls 按入口编号 sorted(set(p [0] for p in prtls ))

计算我的grpd_prtls的曼哈顿距离,每个数字仅配置2个门户

to calc 'Manhatten Distance' from my grpd_prtls, assmuming just 2 portals per number

[[p[0], sum(abs(a-b)
            for a, b in zip(*p[1]))]
 for p in grpd_prtls] 
Out[214]: [['1', 5], ['2', 16]]

这篇关于Python无法比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆