简体   繁体   English

定义一个函数,该函数针对各种字符串python调用另一个函数

[英]defining a function which calls another function for a variety of strings python

I have a code which finds anagrams of a string in a dictionary file. 我有一个代码,可在字典文件中找到字符串的字谜。 I want to create a function which tests a variety of strings called test_find_anagrams(). 我想创建一个测试各种字符串的函数,称为test_find_anagrams()。 It should test at least 6 different strings. 它应该测试至少6个不同的字符串。

This is the code i have which tests a single string in a file. 这是我测试文件中单个字符串的代码。

def anagram(str1,str2):
    str1 = sorted(str1)
    str2 = sorted(str2)
    return str1 == str2

def get_dictionary_word_list():
    with open('dictionarys.txt') as f:
        return f.read().split()

def find_anagrams(str):
    return [word for word in get_dictionary_word_list() if anagram(word,str)]

So far i have this code to test different strings, It works on the first string in the list but doesnt return anything for any string after. 到目前为止,我有这段代码可以测试不同的字符串,它适用于列表中的第一个字符串,但之后的任何字符串均不返回任何内容。 What else do i need to put in the code for it to work? 我还需要在代码中加上什么才能使其正常工作?

def test_find_anagrams():
    stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
    for str1 in stringlist:
        return [word for word in get_dictionary_word_list() if anagram(word,str1)]

It only "works on the first string in the list" because you return from inside the loop. 它仅“在列表中的第一个字符串上起作用”,因为您是从循环内部返回的。 Keep track of your result outside of the loop. 在循环之外跟踪结果。

def test_find_anagrams():
    stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
    result = []
    for str1 in stringlist:
        result.extend(word for word in get_dictionary_word_list() if anagram(word,str1))
    return result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在python中运行js函数调用另一个js函数 - run js function in python which calls another js function Python:在另一个function中定义一个function - Python: defining a function inside another function 用另一个功能定义一个功能 - Defining a function with another function 在Python中,确定一个函数是否调用另一个函数 - In Python, determine if a function calls another function 多进程调用python中另一个函数的函数 - multiprocess a function that calls another function in python 定义一个用于字符串和列表的连接函数。 如何? - Defining a function for concatenation which works for strings and lists. How? python如何执行调用从同一对象调用另一个方法的函数的对象方法 - python how to execute object method that calls a function which calls another method from same object 如何知道调用另一个函数的函数所在的脚本名称? - How to know the script name in which the function which calls another function is in? 我可以在Python Flask中调用带有相同文件并带有url请求的函数吗? - Can I call a function which calls another function with the same file with a url request in Python Flask? theano定义了重复调用另一个函数的函数? - theano define function which repeatedly calls another function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM