【问题标题】:Python not returning and setting valuePython不返回和设置值
【发布时间】:2012-11-30 10:52:32
【问题描述】:

我运行以下命令。 all_possible 设置为文件顶部的 []。

def a_combination(input):
global current_char
for y in range(0,len(str(typed))):
    working_int = int(list(str(input))[current_char])
    print working_int
    if (len(all_possible) == 0):
        all_possible.append(digits_all[working_int-2][0])
        all_possible.append(digits_all[working_int-2][1])
        all_possible.append(digits_all[working_int-2][2])
    else:
        for x in range(0, len(all_possible)):
            x = 3*x
##            Duplicate to setup 3 of the same words in the list
            all_possible.insert(x, all_possible[x])
            all_possible.insert(x, all_possible[x])
##            Now append the 1st possible character to the first version of the working string etc...
            all_possible[x] = all_possible[x]+digits_all[working_int-2][0]
            all_possible[x+1] = all_possible[x+1]+digits_all[working_int-2][1]
            all_possible[x+2] = all_possible[x+2]+digits_all[working_int-2][2]
##            Optimization - check after each stage for no-matches.
    current_char += 1

打印所有可能

    check_matches(all_possible)
print all_possible

def check_matches(input):
    output = []
    for possible_word in input[:]:
        for real_word in word_dictionary:
            if (normalise_word(real_word).startswith(possible_word)):
                output.append(possible_word)
            if (normalise_word(real_word) == possible_word):
                print possible_word, 'is a perfect match with the dictionary.'
    print output
    all_possible = output
    print all_possible
    return all_possible

问题是它没有返回并设置 a_combination 中 all_possible 的值。它在 check_matches 中打印处理后的值,但没有正确返回,这意味着 a_combination 打印了错误的内容(通过 normalise_word 之前的列表)。有什么想法吗?

山姆

【问题讨论】:

  • 介意告诉我们你的代码是关于什么的吗?
  • 这是为了从数字中猜测可能的单词

标签: python list return


【解决方案1】:

您没有保留来自check_possible()all_possible 的返回值。您将输出列表分配给函数内的局部变量,然后将其返回给调用者,然后调用者将其丢弃。你应该这样做

all_possible = check_matches(all_possible)

另外,你应该停止尝试使用全局变量,它们是你困惑的原因。将变量保留在使用它们的函数的本地,并选择不同的名称。

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2021-07-30
    相关资源
    最近更新 更多