首页 > 解决方案 > 如何让函数仅返回与特定字符串匹配的列表?

问题描述

我有以下问题;我有一个元组叫split_content

(['@Book{Clark2003,',
  'author ,   {Eve Clark},',
  'title ,    {First Language Acquisition},',
  'publisher ,    {Cambridge University Press},',
  'address , {Cambridge, UK},',
  'year ,     2003}',
  'volume ,  10}}'],
 ['',
  '@techreport{arrow1948,',
  'author , {Arrow, Kenneth J.},',
  'title , {The possibility of a universal social welfare        function},',
  'institution , {RAND Corporation},',
  'year , {1948},',
  'number , {P-41},',
  'type , {Report}'])

​,如您所见,它已经分为两个子列表(之前[",'@techreport)。
我需要能够获取一个字符串 ( intext2) 并在这两个列表中的任何一个中找到匹配项。例如if intext2[0] = 'Clark'。我希望它只返回第一个子列表,即以 . 结尾的子列表'volume, 10}}']

现在,我编写了这段代码来实现这一点,但它并不总是有效:

def split_file():
    split_content = split_up()
    intext= u_input[u_input.find("(")+1:u_input.find(")")]
    intext2 = re.split('(\d+)',intext) 
    global split_content_fin
    if [intext2[0] in split_content[0]]:
        split_content_fin = split_content[0]
   
    if [intext2[0] in split_content[1]]:
        split_content_fin = split_content[1]
       
    return split_content_fin

通常它只返回第二个子字符串,尽管根本没有匹配intext2[0]。我已经尝试过列表推导而不是[intext2[0]in split_content[0/1]],但无济于事。不过,我觉得问题就在那里,但是,我找不到解决方案。还是与它是一个元组有关?

标签: pythonpython-2.7listtuplesmatch

解决方案


像这样的东西?

split_content = (['@Book{Clark2003,',
  'author ,   {Eve Clark},',
  'title ,    {First Language Acquisition},',
  'publisher ,    {Cambridge University Press},',
  'address , {Cambridge, UK},',
  'year ,     2003}',
  'volume ,  10}}'],
 ['',
  '@techreport{arrow1948,',
  'author , {Arrow, Kenneth J.},',
  'title , {The possibility of a universal social welfare        function},',
  'institution , {RAND Corporation},',
  'year , {1948},',
  'number , {P-41},',
  'type , {Report}'])


asString_1 = ','.join(map(str,split_content[0]))
asString_2 = ','.join(map(str,split_content[1]))
aWord = 'Clark'

if(aWord in asString_1):
    print("in the first element")
elif(aWord in asString_2):
    print("in the second element")
#elif(...)
#   ...

推荐阅读