【问题标题】:Inputing an identical string multiple times to a function [duplicate]多次向函数输入相同的字符串[重复]
【发布时间】:2014-06-17 20:27:34
【问题描述】:

假设我有一个函数,myfunc(*iterables)

我想做以下事情:

myfunc('abc','abc','abc')

但不重复 'abc' 并使用 n(上例中为 =3

我试过了:

myfunc(['abc']*n)

但是这给了

myfunc(['abc', 'abc', 'abc'])

这不起作用。

有没有简单的方法来做到这一点?

【问题讨论】:

    标签: python string list


    【解决方案1】:

    你需要unpack the arguments list,像这样

    myfunc(*['abc']*n)
    

    例如,

    def myfunc(*iterables):
        print iterables
    
    myfunc('abc', 'abc', 'abc')   # 3 Arguments
    # ('abc', 'abc', 'abc')
    myfunc(['abc'] * 3)           # 1 Argument with 3 items in it
    # (['abc', 'abc', 'abc'],)
    myfunc(*['abc'] * 3)          # Unpack the 3 element list, to pass 3 arguments
    # ('abc', 'abc', 'abc')
    

    【讨论】:

    • 对 * 的一些解释?
    • @alvas 刚刚包含了文档中的相关部分。
    【解决方案2】:

    您已将列表转换回参数:

    myfunc(*['abc']*n)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-06
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      相关资源
      最近更新 更多