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

时间:2018-12-18 12:03:37

标签: python python-3.x python-2.7 spyder

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']

#i尝试过

 v=[]

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

    print(v)

fisrt我已创建了一个列表,该列表仅包含姓名在姓名列表中的该人的信息 现在我想像alex一样使用o / p:os_10,peter:OS_9等

4 个答案:

答案 0 :(得分:2)

您可以Split文本并获得 First Last 索引项。

代码:

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

答案 1 :(得分:2)

只需按空格分隔即可获得第一个和最后一个单词。

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)

答案 2 :(得分:1)

只是为了好玩,在这种情况下,请使用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

答案 3 :(得分:0)

使用split()[0]获取第一个单词(由空格分隔,并获取第一个单词),然后使用split()[-1]获取最后一个单词。

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

然后,您可以使用",\n"

加入所有内容
print( ",\n".join(v) )