我想在Python中以某種方式切片列表。如果我有一個看起來像這樣的列表:切片列表建議
myList = ['hello.how.are.you', 'hello.how.are.they', 'hello.how.are.we']
有沒有辦法來切它,這樣我可以每個元素的最後一個句號之後得到的一切?所以,我想要「你」,「他們」和「我們」。
我想在Python中以某種方式切片列表。如果我有一個看起來像這樣的列表:切片列表建議
myList = ['hello.how.are.you', 'hello.how.are.they', 'hello.how.are.we']
有沒有辦法來切它,這樣我可以每個元素的最後一個句號之後得到的一切?所以,我想要「你」,「他們」和「我們」。
是的,這是可以做到:
# Input data
myList = ["hello.how.are.you", "hello.how.are.they", "hello.how.are.we"]
# Define a function to operate on a string
def get_last_part(s):
return s.split(".")[-1]
# Use a list comprehension to apply the function to each item
answer = [get_last_part(s) for s in myList]
# Sample output
>>> answer: ["you", "they", "we"]
速度惡魔腳註:使用s.rpsilt(".", 1)[-1]
是速度甚至比split()
。
[i.split('.')[-1] for i in myList]
沒有辦法直接切片清單;你所做的是切分每個元素。
你可以很容易地建立一個list comprehension你在那裏你split
的時期,並採取最後一個元素。
myList = ["hello.how.are.you", "hello.how.are.they", "hello.how.are.we"]
after_last_period = [s.split('.')[-1] for s in myList]
假設你省略圍繞每個列表元素的報價,使用列表理解和str.split()
:
[x.split('.')[-1] for x in myList]
你忽略了一堆引號? –