0

新手问题,我有以下代码,我需要将变量 gerrit 中的数据与列表 gerrit_refs 匹配并获取相应的匹配并保存在变量中,我该怎么做?

'''
gerrit_refs:
refs/changes/89/202089/4
refs/changes/39/205739/2
refs/changes/94/195594/6
refs/changes/90/202090/4
refs/changes/92/202092/4
'''

def main ():
    gerrit=205739
    with open('gerrit_refs.txt', 'r') as f:
        # Here we make a list of refs based on the file
        gerrit_refs = [line.strip() for line in f]
    match = None
    for ref in gerrit_refs:
        if gerrit in ref:
            match = ref
            print match
            break

if __name__ == '__main__':
    main()

错误:-

TypeError: 'in' 需要字符串作为左操作数,而不是 in

4

2 回答 2

1

过滤掉列表理解中的匹配行:

def main ():
    gerrit = 205739
    gerrit_str = str(gerrit)
    with open('gerrit_refs.txt', 'rb') as f:
        # Here we make a list of refs based on the file
        gerrit_refs = [line.strip() for line in f if gerrit_str in line]

    if gerrit_refs:
        # At least one match was found.
        print gerrit_refs

注意需要将gerrit搜索变量更改为字符串。in运算符不适用于混合变量。

如果有多个引用,这将起作用,因为它返回一个列表。如果您只想获取第一个匹配项,则只需提取第一项:

if gerrit_refs:
    print "First match:", gerrit_refs[0]
于 2012-12-28T19:48:53.667 回答
1
next((l.strip() for l in open('gerrit_refs.txt') if str(gerrit) in l), False)
于 2012-12-28T20:22:40.863 回答