如何从 python 列表中任何特定索引处出现的句子中提取特定字符串?

how to extract a particular string from a sentence present at any particular index in list in python?

names=['alex','peter','sana','alice']

info=['alex is working on os_10 coolest one',
'peter is working on OS_9 which is not that cool', 
'sana is working on OS_7 which is quite old', 
'Thanos is also using os_10', 
'alice is fan of thanos so she also uses os_10']

#我试过了

 v=[]

    for name in names:
        a= [x for x in info if name in x]
        #print(a)
        v.append(a)

    print(v)

首先,我制作了一个列表,其中仅包含名字在姓名列表中的那个人的信息 现在我想要 o/p 像 alex: os_10, peter: OS_9 etc

split()[0]得到第一个词(用空格分割,得到第一个),用split()[-1]得到最后一个词。

v = [ s.split()[0] + " " + s.split()[-1] for s in a ]

然后你可以用",\n"

加入所有东西
print( ",\n".join(v) )

您可以 Split 文本并获取项目 FirstLast 索引。

代码:

a = ['Alex is working on OS_10', 'Peter is working on OS_8', 'Sana is working on OS_7']
print(*[f"{t.split()[0]} {t.split()[-1]}" for t in a], sep=',\n')

输出:

Alex OS_10,
Peter OS_8,
Sana OS_7

简单的用空格分割,得到第一个词和最后一个词。

a = ['Alex is working on OS_10', 'Peter is working on OS_8', 'Sana is working on OS_7']

extracted_list = [(item.split()[0], item.split()[-1]) for item in a]

final_result = '\n'.join((f"{tuple[0]} {tuple[1]}" for tuple in extracted_list))

print(final_result)

只是为了好玩,在这种特殊情况下,使用 slice 来避免将字符串拆分两次。

a = ['Alex is working on OS_10', 'Peter is working on OS_8', 'Sana is working on OS_7']
data = [ ' '.join(line.split()[::4]) for line in a ]

print(data)
['Alex OS_10', 'Peter OS_8', 'Sana OS_7']

你可以根据自己的需要调整切片,因为它是这样工作的

a_list[start_index : end_index : step]

查看这里了解更多信息 https://docs.python.org/2.3/whatsnew/section-slices.html