从PhP到Python的飞跃

2024-10-03 11:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个相当舒服的PHP程序员,很少有Python经验。我试图帮助他的项目伙伴,代码很容易用Php编写,我有它的大部分移植,但需要一点帮助完成翻译,如果可能的话。 目标是:

  • 生成具有uid的基本对象列表
  • 随机选择几个项目来创建第二个列表,该列表键入包含新项目的uid 属性。你知道吗
  • 测试两个列表之间的交叉点以相应地改变响应。你知道吗

下面是我试图用Python编写代码的一个工作示例

<?php
srand(3234);
class Object{  // Basic item description
    public $x       =null;
    public $y       =null;
    public $name    =null;
    public $uid     =null;
}
class Trace{  // Used to update status or move position
#   public $x       =null;
#   public $y       =null;
#   public $floor   =null;
    public $display =null;  // Currently all we care about is controlling display
}
##########################################################
$objects = array();
$dirtyItems = array();

#CREATION OF ITEMS########################################
for($i = 0; $i < 10; $i++){
    $objects[] = new Object();
    $objects[$i]->uid   = rand();
    $objects[$i]->x     = rand(1,30);
    $objects[$i]->y     = rand(1,30);
    $objects[$i]->name  = "Item$i";
}
##########################################################

#RANDOM ITEM REMOVAL######################################
foreach( $objects as $item )
    if( rand(1,10) <= 2 ){  // Simulate full code with 20% chance to remove an item.
        $derp = new Trace();
        $derp->display = false;
        $dirtyItems[$item->uid] = $derp;  //#  <- THIS IS WHERE I NEED THE PYTHON HELP
        }
##########################################################
display();

function display(){
global $objects, $dirtyItems;
    foreach( $objects as $key => $value ){  // Iterate object list
        if( @is_null($dirtyItems[$value->uid]) )  // Print description
            echo "<br />$value->name is at ($value->x, $value->y) ";
        else  // or Skip if on second list.
            echo "<br />Player took item $value->uid";

    }
}
?>

所以,实际上我已经对大部分内容进行了排序,我只是在Python版本的关联数组中遇到了一些问题,即列表的键与主列表中唯一的项数匹配。你知道吗

上述代码的输出应类似于:

Player took item 27955
Player took item 20718
Player took item 10277
Item3 is at (8, 4) 
Item4 is at (11, 13)
Item5 is at (3, 15)
Item6 is at (20, 5)
Item7 is at (24, 25)
Item8 is at (12, 13)
Player took item 30326

我的Python技能仍在学习中,但这与上面的代码块大致相同。 我一直在研究并尝试使用list函数.insert()或.setitem(),但它并没有像预期的那样工作。你知道吗

这是我当前的Python代码,还没有完全实现

import random
import math

# Begin New Globals
dirtyItems = {}         # This is where we store the object info
class SimpleClass:      # This is what we store the object info as
    pass
# End New Globals

# Existing deffinitions
objects = []
class Object:
    def __init__(self,x,y,name,uid):
        self.x = x  # X and Y positioning
        self.y = y  #
        self.name = name #What will display on a 'look' command.
        self.uid = uid

def do_items():
    global dirtyItems, objects
    for count in xrange(10):
        X=random.randrange(1,20)
        Y=random.randrange(1,20)
        UID = int(math.floor(random.random()*10000))
        item = Object(X,Y,'Item'+str(count),UID)
        try: #This is the new part, we defined the item, now we see if the player has moved it
            if dirtyItems[UID]:
                print 'Player took ', UID
        except KeyError:
            objects.append(item) # Back to existing code after this
            pass    # Any error generated attempting to access means that the item is untouched by the player.

# place_items( )
random.seed(1234)

do_items()

for key in objects:
    print "%s at %s %s." % (key.name, key.x, key.y)
    if random.randint(1, 10) <= 1:
        print key.name, 'should be missing below'
        x = SimpleClass()
        x.display = False
        dirtyItems[key.uid]=x

print ' '
objects = []
random.seed(1234)

do_items()

for key in objects:
    print "%s at %s %s." % (key.name, key.x, key.y)

print 'Done.'

所以,很抱歉我发了这么长的帖子,但是我想把这两套完整的代码都提供给大家。PhP工作得很好,Python也很接近。如果有人能给我指出正确的方向,那将是一个巨大的帮助。 dirtyItems.insert文件(密钥.uid,x)是我试图用来使列表作为关联数组工作的

编辑:轻微修正。


Tags: thekey代码name列表uidobjectsis
2条回答

创建字典而不是数组:

import random
import math

dirtyItems = {}

然后你可以使用:

dirtyItems[key.uid] = x

您将dirtyItems声明为数组而不是字典。在python中,它们是不同的类型。你知道吗

改为dirtyItems = {}。你知道吗

相关问题 更多 >