拆分然后删除理解中的最后一个字符
Splitting and then removing last character in comprehension
我正在尝试在 python 中编写理解以拆分字符串,然后删除结果列表中每个元素的最后一个字符,例如:
>>> text = "firstX secondY thirdZ"
>>> split_text = < some code >
>>> print(split_text)
['first','second','third']
我可以让它做我想做的事而无需理解:
>>> text = "firstX secondY thirdZ"
>>> split_text = []
>>> for temp in text.split():
... split_text.append(temp[:-1])
...
>>> print(split_text)
['first', 'second', 'third']
但我想学习如何在一次理解中做到这一点..
你可以这样做:
splittext = [x[:-1] for x in text.split()]
试试下面的方法
text = "firstX secondY thirdZ"
text_lst = [x[:-1] for x in text.split(' ')]
print(text_lst)
输出
['first', 'second', 'third']
我正在尝试在 python 中编写理解以拆分字符串,然后删除结果列表中每个元素的最后一个字符,例如:
>>> text = "firstX secondY thirdZ"
>>> split_text = < some code >
>>> print(split_text)
['first','second','third']
我可以让它做我想做的事而无需理解:
>>> text = "firstX secondY thirdZ"
>>> split_text = []
>>> for temp in text.split():
... split_text.append(temp[:-1])
...
>>> print(split_text)
['first', 'second', 'third']
但我想学习如何在一次理解中做到这一点..
你可以这样做:
splittext = [x[:-1] for x in text.split()]
试试下面的方法
text = "firstX secondY thirdZ"
text_lst = [x[:-1] for x in text.split(' ')]
print(text_lst)
输出
['first', 'second', 'third']