【问题标题】:How do I get a function to return only the list which matches a particular string?如何让函数只返回与特定字符串匹配的列表?
【发布时间】:2019-02-08 08:53:30
【问题描述】:

我有以下问题;我有一个名为 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] 完全不匹配,但它通常只返回第二个子字符串。我已经在split_content[0/1]] 中尝试了列表推导而不是[intext2[0],但无济于事。不过,我觉得问题就在那里,但是,我找不到解决方案。还是与它是一个元组有关?

【问题讨论】:

  • 对第二个 if 语句和 else 语句使用和 elif 语句,它'打印(“未找到匹配”)'以进行错误跟踪

标签: python python-2.7 list tuples match


【解决方案1】:

这样的?

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(...)
#   ...

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多