【问题标题】:python - return and print does not give same resultpython - 返回和打印不给出相同的结果
【发布时间】:2014-09-24 05:54:40
【问题描述】:

我要做的是将输入的以逗号分隔的字符串更改为列表,然后为每个列表作为键打印关联的值。

def main():
    myDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5....}
    u_input = input("Enter a letter")
    myList = [x.strip() for x in u_input.split(',')]
    result = searchDict(myList)
    print(result)

def searchDict(key):
    for ml in key:
        value = myDict.get(ml, "not found")
        re = []
        re.append(value)
        print('-'.join(re)) #this one shows each value for each entered key separated by comma but it does not print it in one line also prints 'None' on the end

    #res = '-'.join(re)
    #return res //this only shows the value for the first key only even if I enter multiple letter

main();

问题是,如果我返回 'res' 而不是打印它,我只会得到第一个键值。

用打印输出(如果我输入a,b):1, 2, none

输出并返回1

【问题讨论】:

  • 如果你显示你的输出,这可能是一个更好的问题!
  • @Kasra,我已经包含了我得到的内容。
  • 另外,您必须注意代码的缩进、语法和验证!拒绝投票!
  • @Kasra,好的。

标签: python


【解决方案1】:

这些行是否正确缩进?

for ml in key:
value = myDict.get(ml, "not found"); 
re = [];
re.append(value)

我认为您希望它这样做:

re = []
for ml in key:
    value = myDict.get(ml, "not found")    
    re.append(value)
return '-'.join(re)

顺便说一句,Python 中没有使用分号。

【讨论】:

  • 谢谢,工作。我只是在这里再次输入代码,这就是原因。
【解决方案2】:

我认为这是因为您在每个循环中都重置了re。尝试将 re=[] 放在 for 循环之外。

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 2015-12-29
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多