我有这个代码输出(使用键盘模块):
[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
如何从此列表中删除每个'KeyboardEvent'?
答案 0 :(得分:6)
如何使用KeyboardEvent.name
:
newList = [event.name for event in myList]
要获得更好的结果,您可以将其与KeyboardEvent.event_type
结合使用:
newList = [event.name + ' ' + event.event_type for event in myList]
演示:
>>> myList
[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down)]
>>> [event.name for event in myList]
['enter', 'h', 'h', 'e', 'e', 'y']
>>> [event.name + ' ' + event.event_type for event in myList]
['enter up', 'h down', 'h up', 'e down', 'e up', 'y down']
答案 1 :(得分:3)
a=[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
a=[elem for elem in a if not isinstance(a, KeyboardEvent)]
此列表补偿应该有效
答案 2 :(得分:2)
我会尝试正则表达式
import re
Foo = [KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
strList = []
for item in Foo:
bar = re.sub('KeyboardEvent(\(.*?)', '', str(item))
bar = re.sub('\)', '', bar)
strList.append(bar)
print strList
答案 3 :(得分:1)
尝试使用循环删除它:
list = [KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
for x in list:
del list[str(x)]
答案 4 :(得分:1)
或者您可以尝试将其实际删除KeyBoard事件作为字符串:
a=[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
a=[str(elem).strip('KeyboardEvent') for elem in a]