繁体   English   中英

如何在 python 上打印列表?

[英]how do I print a list on python?

我在 python 中打印列表时遇到问题,因为每当我发出显示列表的命令时,它都不会显示该列表。 下面是整个 function 的代码参考列表在:

    #FUNCTIONS
def help():
    print("list of commands\n"
          + "help = Display of commands\n"
          + "list = list of all the Latin I vocabulary\n"
          + "Quit = exits the main program to the exit credits and then exits the app\n")
def userInstructions(userInput):
    if (userInput == "help" or "Help"):
        help()
    elif(userInput == "list" or "List"):
        list()


    return input("\nEnter your responce: ")


def list():
    a = ["salve" , "vale" , "et" , "est" , "in" , "sunt" , "non" , "insula" , "sed" , "oppidum"
                , "quoque" , "canis" , "coquus" , "filia" , "filius" , "hortus" , "mater" , "pater" , "servus" , "via" , "amicus" , "ancilla" , "cena" , "cibus"
                , "intro" , "saluto" , "porto" , "video" , "dominus" , "laetus" , "mercator" , "audio" , "dico" , "unus" , "duo" , "tres" , "quattuor" , "quinque"
                , "sex" , "septem" , "octo" , "novem" , "decem" , "ad" , "ecce" , "magnus" , "parvus" , "ambulo" , "iratus" , "quis" , "quid" , "cur" , "ubi" ,
                "sum" , "es" , "eheu" , "pecunia" , "ego" , "tu" , "habeo" , "respondeo" , "venio" , "rideo" , "quod" , "ex" , "voco" , "clamo" , "specto" , "taberna"
                , "laboro" , "clamor" , "femina" , "vir", "puer" , "puella" , "multus" , "urbs" , "agricola" , "curro" , "hodie" , "iuvenis" , "meus" , "senex" , "sto" ,
                "optimus" , "volo" , "fortis" , "emo" , "pulso" , "bonus" , "malus" , "festino" , "per" , "pugno" , "scribo" , "tuus" , "erat" , "paro" , "cum" , "facio" ,
                "heri" , "ingens" , "nihil" , "omnis" , "vendo" , "navis" , "prope" , "rogo" , "terreo" , "inquit" , "tamen" , "eum" , "eam" , "duco" , "saepe" , "interficio" ,
                "habito" , "silva" , "statim" , "totus" , "pessimus"]

    print("List:")
    print('\n'.join(map(str, a)))

下图显示了当我命令代码打印列表而不是打印列表时的结果,而是打印帮助面板: 命令结果

我的代码有什么问题,我该如何解决?

userInput == "help" or "Help"被 Python 解释为(userInput == "help") or "Help" ,这将始终为真。 而是尝试:

userInput == "help" or userInput == "Help"

或者

userInput in ["help","Help"]

或者

userInput.lower() == "help"

(同样对于userInput == "list" or "List" )。

另外我不建议命名您的 function list() ,它与内置的 python function 冲突。

罪魁祸首是:

if (userInput == "help" or "Help"):

你需要:

if userInput in ('help', 'Help'):

或者:

if userInput == 'help' or userInput == 'Help':

'==' 的优先级大于 'or',因此您的 'if' 被视为:

if (userInput == 'help') or ('Help'):

因为“帮助”在逻辑上等同于“真”,所以你永远不会通过第一个if检查。

当您想要不区分大小写时,只需在检查之前转换为全部大写或小写。 所以你也可以说:

if userInput.lower() == 'help':

有许多不同的方法可以做到这一点。 有些人认为某些方式比其他方式好得多。 但诀窍是让它发挥作用。 快乐编码!

另外,作为旁注,您可以只说'\n'.join(a)没有mapstr ,因为看起来列表中的所有条目都已经是字符串。 如果您可能还有其他东西,那么mapstr很有帮助。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM