如何在比较python中的两个列表时只返回一个列表中元素的索引

时间:2015-11-11 19:30:52

标签: python indexing

我已经编写了这段代码,但它没有给出任何结果。

text1=list(text)
pattern1=list(pattern)
for q in range(0,m):  
for r in range(0,n):
    if text1[q]==pattern1[r]:
        return q

1 个答案:

答案 0 :(得分:0)

一个问题是您使用的是 return 语句,但您不在函数中。在某些Python系统中,它只会退出主程序。我尝试了你的代码的再现,它运行得很好。我必须对你的输入风格做一些假设;我希望他们是对的。

text = """
Now I will a rhyme construct
By chosen words the young instruct
Cunningly ensured endeavour
Con it and remember ever
Widths of circle here you see
Stretched out in strange obscurity
"""
pattern = ("falafel", "ensured", "pizza", "strange")

text1=text.split()
pattern1=list(pattern)

print text1
for q in range(0,len(text1)):
    for r in range(0,len(pattern1)):
        if text1[q]==pattern1[r]:
            print q

我得到的输出正确识别“确定”和“奇怪”的命中。

Now I will a rhyme construct
By chosen words the young instruct
Cunningly ensured endeavour
Con it and remember ever
Widths of circle here you see
Stretched out in strange obscurity

['Now', 'I', 'will', 'a', 'rhyme', 'construct', 'By', 'chosen', 'words', 'the', 'young', 'instruct', 'Cunningly', 'ensured', 'endeavour', 'Con', 'it', 'and', 'remember', 'ever', 'Widths', 'of', 'circle', 'here', 'you', 'see', 'Stretched', 'out', 'in', 'strange', 'obscurity']
13
29