Python可变参数用法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了Python可变参数用法。分享给大家供大家参考,具体如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def calc(*numbers):
  sum=0
  for n in numbers:
    sum+=n**2
  return sum
print(calc(1,2,3))
print(calc(1,3,5,7))
print(calc())

运行效果图如下:

定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数。

Python允许你在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def calc(*numbers):
  sum=0
  for n in numbers:
    sum+=n**2
  return sum
nums = [1,2,3]
print(calc(*nums))

运行效果图如下:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

使用pandas 将DataFrame转化成dict

直接转换就行了,key为DataFrame的column; import pandas as pd data = pd.read_csv('./input/month_6_1.cs...

Python编程中对super函数的正确理解和用法解析

当在子类需要调用父类的方法时,在python2.2之前,直接用类名调用类的方法,即非绑定的类方法,并把自身对象self作参数传进去。 class A(object): def...

python解析中国天气网的天气数据

使用方法:terminal中输入复制代码 代码如下:python weather.py http://www.weather.com.cn/weather/101010100.shtml...

浅谈Python中的闭包

Python中的闭包的概念, 在我看来, 就相当于在某个函数中又定义了一个或多个函数, 内层函数定义了具体的实现方式, 而外层返回的就是这个实现方式, 但并没有执行, 除非外层函数调用的...

Python模块_PyLibTiff读取tif文件的实例

Usage example (libtiff wrapper) from libtiff import TIFF # to open a tiff file for reading:...