[英]How do I remove part of a string in python list?
我有这个代码输出(使用键盘模块):
[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
如何从此列表中删除每个“KeyboardEvent”?
如何使用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']
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)]
这个清单应该有效
我会尝试正则表达式
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
尝试使用循环删除它:
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)]
或者你可以试试这个实际上将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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.