【问题标题】:How to Use a Python List as Arguments in a Function如何在函数中使用 Python 列表作为参数
【发布时间】:2020-07-13 12:25:15
【问题描述】:

如果我有一个 Python 列表,其中包含一列参数和值,例如:

[('Title','Test'),('Year','1990'),('Date','1/2/1900')]

我想把它传递给一个函数,让它看起来像这样:

function('Title' = 'Test', 'Year' = '1990', 'Date' = '1/2/1900')

最好的方法是什么?

【问题讨论】:

  • function(**dict(that_list))?
  • 回答我上面的问题,假设您的意思是function(Title='Test', Year='1990'...),因为您在问题中使用的语法不正确。

标签: python list function arguments


【解决方案1】:

将列表转换为字典并将其传递给函数。

代码

x=[('Title','Test'),('Year','1990'),('Date','1/2/1900')]
d = dict(x)

def function(data):
  print(data)
  pass # write whatever you wanna do with your function

function(d)

输出

{'Title': 'Test', 'Year': '1990', 'Date': '1/2/1900'}

【讨论】:

  • 相同。这需要一个位置参数,即字典本身。
  • 其实是的,我更新了答案。我的意思是这样 OP 可以实现他正在寻找的东西。
  • 但是,如果我能想出任何方法,我会在我的答案中添加其他方法。谢谢
猜你喜欢
  • 1970-01-01
  • 2011-06-26
  • 2013-05-11
  • 2020-10-07
  • 2012-04-02
  • 2018-08-05
  • 2018-08-10
  • 2012-04-03
  • 2023-01-30
相关资源
最近更新 更多