[英]How do I remove part of a string in python list?
I have this output of code (used keyboard module): 我有这个代码输出(使用键盘模块):
[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]
How can I remove every 'KeyboardEvent' from this list? 如何从此列表中删除每个“KeyboardEvent”?
How about using KeyboardEvent.name
: 如何使用
KeyboardEvent.name
:
newList = [event.name for event in myList]
To get an even better result you can combine this with KeyboardEvent.event_type
: 要获得更好的结果,您可以将其与
KeyboardEvent.event_type
结合使用:
newList = [event.name + ' ' + event.event_type for event in myList]
Demo: 演示:
>>> 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)]
This list comprehesion should work 这个清单应该有效
I would try regular expressions 我会尝试正则表达式
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
Try to remove this using a loop: 尝试使用循环删除它:
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)]
Or you could try this which actually removes the KeyBoard event as a string: 或者你可以试试这个实际上将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.