重新编码一个命名元组

时间:2017-09-04 14:08:27

标签: python class tuples named

输入:

import mouse
import pickle
from collections import namedtuple

#https://github.com/boppreh/keyboard/blob/master/keyboard/mouse.py

#from ._mouse_event import ButtonEvent, MoveEvent, WheelEvent, LEFT, RIGHT, 
MIDDLE, X, X2, UP, DOWN, DOUBLE


ButtonEvent = namedtuple('ButtonEvent', ['event_type', 'button', 'time'])
WheelEvent = namedtuple('WheelEvent', ['delta', 'time'])
MoveEvent = namedtuple('MoveEvent', ['x', 'y', 'time'])

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

#print (type (itemlist))
print (itemlist[:3])

z=0
xx=50
yy=10
itemlist2=[]

for i in itemlist:
    old_event = itemlist[z]
    new_event = MoveEvent(x=xx, y=yy, time=old_event.time)
    itemlist2.append(new_event)
    z=z+1
    xx=xx+1
    yy=yy+1
print ()

print (itemlist2[:3])

print (type (itemlist))
print (type (itemlist[0]))
print (type (itemlist[0][0]))

print()

print (type (itemlist2))
print (type (itemlist2[0]))
print (type (itemlist2[0][0]))

输出:

[MoveEvent(x=1369, y=162, time=1504533266.029788), MoveEvent(x=1358, y=165, time=1504533266.0377884), MoveEvent(x=1350, y=167, time=1504533266.045789)]

[MoveEvent(x=50, y=10, time=1504533266.029788), MoveEvent(x=51, y=11, time=1504533266.0377884), MoveEvent(x=52, y=12, time=1504533266.045789)]
<class 'list'>
<class 'mouse._mouse_event.MoveEvent'>
<class 'int'>

<class 'list'>
<class '__main__.MoveEvent'>
<class 'int'>

这里的python新手 - 当我将命名元组列表重新组合到itemlist2时,我需要保留 -class mouse._mouse_event.MoveEvent - - 不确定如何做到这一点

我想我也可以尝试编辑&#39; itemlist&#39;如果可能,直接

打印时,列表看起来相同(除了更改的值)

1 个答案:

答案 0 :(得分:0)

您在文件中创建了一个新的MoveEvent namedtuple类型:

MoveEvent = namedtuple('MoveEvent', ['x', 'y', 'time'])

如果您想使用原件,则需要使用mouse._mouse_event.MoveEvent或重命名以上内容:

MoveEvent = mouse._mouse_event.MoveEvent

因为mouse.py包含以下行:

from ._mouse_event import ButtonEvent, MoveEvent, WheelEvent, LEFT, RIGHT, MIDDLE, X, X2, UP, DOWN, DOUBLE

您可以使用此代码:

import mouse
from mouse import MoveEvent