简体   繁体   English

如何将元组传递给python函数

[英]How to pass a tuple to a python function

I've been trying to pass a tuple to a function that I created earlier, however, I m still not able to make it work. 我一直试图将元组传递给我先前创建的函数,但是,我仍然无法使它起作用。 My objective is to pass a tuple containing a list of path+file form which I want to discover the size and print it out. 我的目标是传递一个包含路径+文件格式列表的元组,我想发现它的大小并打印出来。

Here's my code 这是我的代码

EXl = ('C:\\vd36e404.vdb','C:\\vd368c03.vdb')

def fileF(EXl):
    import os
    filesize = os.path.getsize(EXl)
    print (filesize);

fileF(EXl)

These are the errors: 这些是错误:

Traceback (most recent call last):
  File "C:\Documents and Settings\Administrator\workspace\test1py\testcallMyF.py", line 13, in <module>
    fileF(EXl)
  File "C:\Documents and Settings\Administrator\workspace\test1py\testcallMyF.py", line 9, in fileF
    filesize= os.path.getsize(EXl)
  File "C:\Python27\lib\genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
TypeError: coercing to Unicode: need string or buffer, tuple found

Could anyone explain to me why?(I'm using Python 2.7.2) 谁能向我解释原因?(我使用的是Python 2.7.2)

You're successfully passing the tuple to your own function. 您已成功将元组传递给自己的函数。 But os.path.getsize() doesn't accept tuples, it only accepts individual strings. 但是os.path.getsize()不接受元组,它仅接受单个字符串。

Also, this question is a bit confusing because your example isn't a path + file tuple, which would be something like ('C:\\\\', 'vd36e404.vdb') . 另外,这个问题有点令人困惑,因为您的示例不是路径+文件元组,它类似于('C:\\\\', 'vd36e404.vdb')

To handle something like that, you could do this: 要处理类似的事情,您可以这样做:

import os

def fileF(EXl):
    filesize= os.path.getsize(EXl[0] + EXl[1])
    print (filesize);

If you want to print values for multiple paths, do as Bing Hsu says, and use a for loop. 如果要打印多个路径的值,请按照Bing Hsu的说明进行操作,并使用for循环。 Or use a list comprehension: 或使用列表理解:

def fileF(EXl):
    filesizes = [os.path.getsize(x) for x in EXl]
    print filesizes

Or if you want to, say, return another tuple: 或者,如果您想返回另一个元组:

def fileF(EXl):
    return tuple(os.path.getsize(x) for x in EXl)
import   os

for xxx in EXl:
    filesize= os.path.getsize(xxx)
    print (filesize);

A way more elegant example: 一个更优雅的例子:

map(fileF, EX1)

This will actually call fileF separately with each of the elements in EX1. 实际上,这将与EX1中的每个元素分别调用fileF。 And of course, this is equivalent to 当然,这等效于

for element in EX1:
    fileF(element)

Just looks prettier. 看起来更漂亮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM