【问题标题】:how to extract a particular string from a sentence present at any particular index in list in python?如何从python列表中任何特定索引处的句子中提取特定字符串?
【发布时间】:2019-05-18 20:17:58
【问题描述】:
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

【问题讨论】:

  • 你试过什么?请发帖MCVE
  • 您要提取列表中句子的第一个和最后一个单词吗?规则是什么?

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


【解决方案1】:

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

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

然后你就可以用",\n"加入一切了

print( ",\n".join(v) )

【讨论】:

    【解决方案2】:

    您可以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
    

    【讨论】:

    • 假设名称是否存储在另一个列表中(比如 name['Alex','Sana','peter','Alice'] )并且列表 [a] 中给出的信息不包含固定模式(例如,如果我们不知道操作系统在 [-1] 中),但我们知道在名称列表中有一个名称可以/不能与 list[a] 中的名称匹配,如果匹配,则应打印对应的名称和使用的操作系统?
    • @DIWAKARMISHRA 我不太清楚。你能展示你尝试过的代码片段吗?此外,您不能指望别人为您编写代码;我们可以帮助解决您遇到的问题。
    • 嘿,我已经修改了,你能检查一下吗
    【解决方案3】:

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

    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)
    

    【讨论】:

    • 使用json是多余的
    • @prashantrana 只是为了打印结果
    • 一个简单的 print(*result,sep='\n') 就可以了。
    • @prashantrana 假设如果名称存储在另一个列表中(比如 name['Alex','Sana','peter','Alice'] )并且列表 [a] 中给出的信息不包含固定模式(例如,如果我们不知道操作系统在 [-1] 中),但我们知道在名称列表中有一个名称可以/不能与 list[a] 中的名称匹配,如果匹配则它应该打印相应的名称和使用的操作系统吗?
    • @DIWAKARMISHRA 如果您想获得操作系统并且知道操作系统是否存在,那么请使用regular expression 获得结果。如果名称在另一个列表中休息,并且您想在 [a] 中检查该名称,那么您也可以通过检查每个列表是否存在来做到这一点。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      相关资源
      最近更新 更多