【问题标题】:Obtain integers from list of mixed data types [duplicate]从混合数据类型列表中获取整数[重复]
【发布时间】:2017-10-31 15:49:00
【问题描述】:

我有一个包含混合数据类型(整数和包含整数的元组)的列表,它们表示列表files 中的文件索引。我想以不同于普通整数的方式处理元组,因为我需要汇总从每个文件计算的数字。如果我遍历列表ind 并检查条目是否为元组并将其传递给函数find_fname,为什么它会在每个条目之后打印出None?这是一个最小的工作示例:

def find_fname(ind, files):
    print files[ind]


files = ['file1','file2','file3','file4']

ind = [0,(1,2),3]

for thing in ind:
    #check to see if entry in list is tuple
    if hasattr(thing, '__iter__'):
        print find_fname(thing[0],files)
        print find_fname(thing[1],files)
    else:
        print find_fname(thing,files)

返回:

file1
None
file2
None
file3
None
file4
None

我想看到find_fname返回:

file1
file2
file3
file4

【问题讨论】:

    标签: python list indexing tuples


    【解决方案1】:

    函数find_fname 的返回值是None,因为您打印该值而不是返回它。如果一个函数没有返回任何东西,它会隐式返回None

    你应该做的是:

    def find_fname(ind, files):
        return files[ind]
    

    【讨论】:

    • 你不能从函数中打印?
    • 是的,你可以,但是你已经在你的代码中打印了返回值,比如print find_fname(...),所以你最终打印了两次。
    • 好的,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2016-03-14
    • 2019-05-18
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多