编辑列表中的项目 pandas

Editing items in a list pandas

我有一个名为 Q395tenleastwords 的列表:

[("'rising", 10), ("'childhood", 10), ("'lasted", 10),("'moore", 10), ("'drug", 10)]

我想编辑列表,只保留单词,所以输出是:

['rising', 'childhood', 'lasted', 'moore', 'drug']

有人可以帮我解决这个问题吗?

使用 list comprehensionindexingslicing:

l = [("'rising", 10), ("'childhood", 10), ("'lasted", 10),("'moore", 10), ("'drug", 10)]

[x[0][1:] for x in l]

输出:

['rising', 'childhood', 'lasted', 'moore', 'drug']

使用 str.lstriplist 理解从每个元组中检索第一个元素:

>>> L = [("'rising", 10), ("'childhood", 10), ("'lasted", 10),("'moore", 10), ("'drug", 10)]
>>> words = [e[0].lstrip("'") for e in L]
>>> words
['rising', 'childhood', 'lasted', 'moore', 'drug']

str 方法接受从末尾删除多个字符,因此如果您想从字符串的两端删除单引号和双引号,我建议:

str.strip('"\'')