如何在Python列表中删除字符串的一部分?

3
我使用键盘模块,得到了以下的代码输出结果:
[KeyboardEvent(enter up), KeyboardEvent(h down), KeyboardEvent(h up), KeyboardEvent(e down), KeyboardEvent(e up), KeyboardEvent(y down), KeyboardEvent(y up)]

如何从此列表中删除每个“KeyboardEvent”?

5
请明确您列表中的元素。该列表中似乎没有字符串,而是对象(KeyboardEvent类的各个实例)。 - Prune
最简单的方法就是 list = []。您是否想要删除特定键盘操作(例如“enter up”)所包含的特定事件? - Ajax1234
5个回答

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']

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)]

这个列表推导式应该可以工作。

不能怪你按照他的要求去做,但这会产生一个空列表,而这显然不是目标。 - Paulo Almeida
@ChristianDean 我不知道。你能解释一下为什么吗? - Ajax1234
@ChristianDean,这是你想要的吗? - whackamadoodle3000
@Ajax1234 当然。 这是首选,因为instance考虑了子类,而type没有考虑。 这是文档中相关的部分。 (https://docs.python.org/3/library/functions.html#type). - Christian Dean

3
我会尝试正则表达式。
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

1
运行良好,但我仍然更喜欢@Vinícius Aguiar的答案。无论如何,点赞。 - Mr.Someone5352

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)]

如果不是键盘事件会怎样? - whackamadoodle3000
它仍然可以工作。它适用于删除列表/数组中的任何内容。 - Oqhax
4
那么你也可以使用 list=[] - whackamadoodle3000
真的,简单多了。 - Oqhax
3
Python 中不建议将 list 作为变量名。 - Vinícius Figueiredo

1

或者你可以尝试这个方法,它实际上将键盘事件作为字符串移除:

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]

(输入向上箭头),KeyboardEvent(h按下),KeyboardEvent(h松开),KeyboardEvent(e按下),KeyboardEvent(e松开),KeyboardEvent(y按下),KeyboardEvent(y松开)。它只会删除第一个。 - Mr.Someone5352

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接