本文介绍了理解 Python 中的元组和 *args 的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个接受可变参数的函数.参数的数量可能从 1 到 N 不等.

I need a function which would be taking variadic arguments. The number of arguments may vary from 1 to N.

def abc(*args):
    print "ABC"
    print args
    print len(args)

def abc1(*args):
    print "ABC1"
    print args
    print len(args)
    print "------------"


tup = ("Hello123")
abc(*tup)
abc1(tup)
tup = ("Hello123", "Hello1234")
abc(*tup)
abc1(tup)

上述程序的输出为;

ABC
('H', 'e', 'l', 'l', 'o', '1', '2', '3')
8
ABC1
('Hello123',)
1
------------
ABC
('Hello123', 'Hello1234')
2
ABC1
(('Hello123', 'Hello1234'),)
1
------------

如果我查看这个输出,当我在 abc1() 中只传递 1 个参数时,元组的长度变为 8(保持 *tup),在 abc1() 中,它显示的长度是 1.为什么以及如何?但是当我在上面的代码中传递 2 个参数时,同样的工作并没有不同.输出为 tupletuple of tuple.如何解决这个问题,因为我必须编写适用于所有 N 的代码

If I look into this output,when i am passing only 1 argument in abc1(), the length of tuple becomes 8(keeping *tup), where as in the abc1() it shows the length is 1. why and how?But the same is not working differently when I am passing 2 arguments in the code above. The output comes as tuple and tuple of tuple.How to resolve this problem because I have to write the code which will work for all N

推荐答案

圆括号不构成元组,逗号可以.要构建单元素元组,正确的语法是

Parentheses don't make tuples, commas do. To build a single-element tuple, the correct syntax is

tup = ("Hello123",)  # parentheses are optional but help readability

相当于

tup = "Hello123",

记住你可以写

x, y = y, x  # swaps x and y using tuple packing/unpacking

一样好

(x, y) = (y, x)

括号是强制的唯一例外是空元组().

The only exception where parentheses are mandatory is the empty tuple ().

这篇关于理解 Python 中的元组和 *args 的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 19:30
查看更多