【问题标题】:How to use square bracket after calling function in Python在Python中调用函数后如何使用方括号
【发布时间】:2020-10-23 15:23:37
【问题描述】:

我想在调用函数后使用方括号。是这样的

function()['名称']

我希望输出为“Andy”。 def 函数语法应该如何?我总是得到错误,说它不可下标。这是我当前的代码

def function1():
    A={'Name':'Andy'}
    return 

function1()['Name']

【问题讨论】:

  • 该函数必须返回一些可下标的内容,例如 e。 G。一个字典。
  • 您的用例不清楚。你想用它来达到什么目的?或许可以举一个输入和输出的例子。

标签: python list function dictionary brackets


【解决方案1】:

我不太明白你的问题。但是如果你想使用方括号,并通过字符串查找你的值,你应该使用字典。 所以功能和打印应该是这样的 ``

def function():
    return {'Name':'andy'}
print(function()['Name'])

EDIT: You can do something like this, and that will print the answer, but i dont think its really practicall, because, yo are not storing the name anywhere

def function():
    return {'Name':print('Andy')}

function()['Name']

【讨论】:

  • 谢谢,它有效,但我们可以在没有print 的情况下给安迪打电话吗?
【解决方案2】:

为此,function 必须返回 dict

def function():
    return {'Name': 'Andy', 'Age': 20}

>>> function()['Name']
'Andy'

在您的示例中,您可以将函数修改为以下内容

def function1():
    A = {'Name': 'Andy'}
    return A

【讨论】:

  • 要让输出显示'Andy',它需要是``` print(function()['Name']) ``` 我们可以调用'Andy;没有print?
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
相关资源
最近更新 更多