Python - return 的功能问题

Python - issues with return in function

我使用的是 csv (csv_f),它基本上只是单引号、逗号分隔的单词:

'foo','bar','yada', 'foo'
'test'

我正在尝试在另一个文档 (csv_g) 中查找这些内容,如下所示:

1 'foo'
2 'bar'
3 'something'
4 'test'

并使用它来构建格式为

的稀疏向量
SparseVector(#lines in csv_g, [#s in first column of csv_g], [# of occurences of each in csv_f])

上面的例子看起来像这样:

(4, [1, 2], [2, 1])
(4, [4], [1])

我已经研究了一段时间并尝试了几种不同的方法,但它们都不起作用。我什至还没有尝试处理像上面 'foo' 这样的多次出现。我最接近的方法是:

import csv

f = open(r'/path/to/csv_f.txt')
g = open(r'/path/to/csv_g.txt')
csv_f = csv.reader(f)
csv_g = csv.reader(g, delimiter=' ')

def lookup(text):
    for row_g in csv_g:
        if row_g[1] == text:
            return (row_g[0])
            break

for row_f in csv_f:
    positions = []
    counts = []
    size = len(row_f)
    i=0
    for i in range(size):
        fword = row_f[i]
        positions.append(lookup(fword))
        counts.append(1)
    print(positions, counts)

运行 这导致:​​

[None, None, None, None] [1, 1, 1, 1]
[None] [1]

我很困惑为什么函数是 returning None 而不是匹配。我以为它会匹配,return 它,然后退出...

我还尝试了一些没有定义查找函数的嵌套循环(如果有帮助,我可以 post 这些尝试,现在我不想弄乱你的屏幕),但这并没有奏效任何一个。我认为这可能是因为生成器只能搜索一次,但我不太确定。

任何有关最佳方法的提示,以及 return 未按预期工作的原因,将不胜感激。

我按照 Claudiu 和 Padriac 的建议解决了这个问题。更新代码:

import csv

f = open(r'/path/to/csv_f.txt')
g = open(r'/path/to/csv_g.txt')
csv_f = csv.reader(f)
csv_g = csv.reader(g, delimiter=' ')

dict = []

for row_g in csv_g:
    dict.append(row_g)
for row_f in csv_f:
    positions = []
    counts = []
    size = len(row_f)
    i=0
    while i<size:
        fword = row_f[i]
        for line in dict:
            gword = line[1]
            if fword == gword:
                positions.append(line[0])
                counts.append(1)
                break
        i+=1
    print(positions, counts)

我不确定为什么查找功能没有得到匹配,但我很高兴我终于能够让一些东西工作!