我的问题如下: 我有一个列表:
list="In the end Tom loves Julie. Fred and Tina are a lot better with dogs.I don't think Jack and Jenny belong together."
首先我做了一个功能
def find_names(Sentence):
Sentence= [x for x in Sentence.replace(',', '').split() if x[0].isupper()]
return Sentence
通过这个,我返回了以大写字母开头的单词。
现在我必须写一个函数
def find_pairs:
应返回每个句子中的对列表。如果句子中有3个大写单词,那么它应该删除第一个单词(假设它是句子的第一个单词),然后返回另外两个单词。我的回报应该如下所示(列表示例:)
[[Tom,Julie],[Fred,Tina],[Jack,Jenny]]
非常感谢你的帮助。
答案 0 :(得分:0)
这是一个相对凌乱的列表理解应该做的伎俩
>>> l = "In the end Tom loves Julie. Fred and Tina are a lot better with dogs.I don't think Jack and Jenny belong together."
>>> [[i for i in j.split() if i[0].isupper()][-2:] for j in l.split('.') if j]
[['Tom', 'Julie'], ['Fred', 'Tina'], ['Jack', 'Jenny']]
答案 1 :(得分:0)
您可以使用zip
执行此类操作
l[0::2]
将从0开始每2个位置获取元素,对于l [1 :: 2]相同但从1开始,并且反转它们,因为我们需要在长度为奇数时消除第一个元素。我们使用[::-1]
Sentence="In the end Tom loves Julie. Fred and Tina are a lot better with dogs.I don't think Jack and Jenny belong together."
l=[x for x in Sentence.replace(',', '').split() if x[0].isupper()]
print [[x,y] for x,y in zip(l[1::2][::-1],l[0::2][::-1])]
答案 2 :(得分:0)
稍作修改,结束函数如下所示:
def find_pairs(text):
return [names[len(names)==3:] for names in ([word.replace(",", "") for word in sentence.split() if word.istitle()] for word in text.split(".")) if 2 <= len(names) <= 3]