php - 从 PhP 到 Python 的飞跃

标签 php python associative-array

我是一个相当熟练的 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 技能还可以,但这与上面的代码块大致相同。 我一直在查看并尝试使用列表函数 .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(key.uid,x) 是我试图用来使列表作为 Assoc 数组工作的东西

编辑:小修正。

最佳答案

您将 dirtyItems 声明为数组而不是字典。在 Python 中,它们是不同的类型。

改为执行 dirtyItems = {}

关于php - 从 PhP 到 Python 的飞跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14018140/

相关文章:

php - 在 php 的 foreach 循环中更改关联数组的 $key

javascript - 当加载的内容具有特殊字符时,使用 html() 加载动态数据会破坏脚本

php - Carbon 语言环境不被尊重?

php - PHP 中的 Z 分数到百分位数

PHP关联数组排序

javascript - 如何根据 JavaScript 中包含对象的属性值对关联对象进行排序

php - 完成 : for Z companies, 计算 A 在 X 天内的平均值。我现在怎么: return value of B for day X for company with highest average of A?

Python:如何根据星期几获取数据框中某个范围内的项目数?

python - sklearn - 模型保持过度拟合

python - OpenCV:在 numpy 数组上查找轮廓