python - 如何让函数仅返回与特定字符串匹配的列表?
问题描述
我有以下问题;我有一个元组叫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]]
,但无济于事。不过,我觉得问题就在那里,但是,我找不到解决方案。还是与它是一个元组有关?
解决方案
像这样的东西?
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(...)
# ...
推荐阅读
- material-ui - 自动完成列表项
- python - 在虚拟环境中制作现有软件包版本 Stick
- javascript - 如何在日历中将 endDate 设置为不早于 startDate?
- google-cloud-platform - 如何在同一个入口处理子路由和根路由
- tar - 使用 pv 进度条提取 .tar.xz
- nsdecimalnumber - NSDecimalNumber 使用库存 NumberFormatter 丢失精度
- asp.net - .Net Core API 与 ReactJS 应用程序。错误翻译应该存储在哪里?
- sql - 在 Hive 中将复杂数据类型与 NULL 合并
- yocto - bitbake 第二次成功构建,而不是第一次使用 devtool
- javascript - 取消输入类型=“文件”上的事件隐藏