Skip to main content
 首页 » 编程设计

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

2025年05月04日29cmt

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) 

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

请您参考如下方法:

您可以拆分 文本并获取项目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