列表在python中返回元组

时间:2014-11-25 00:49:34

标签: python list tuples

我是python的新手。我正在尝试创建一个函数,它将string和list作为参数,并为字符串中找到的每个列表元素(这应该作为元组返回)返回一个布尔值。我试过以下代码

def my_check(str1, list1):
    words = str1.split()
    x = 1
    for l in range(len(list1)):
        for i in range(len(words)):
            if list1[l] == words[i]:
                x = x+1
        if (x > 1):
            print(True)
            x = 1
        else:
            print(False)

output = my_check('my name is ide3',  ['is',  'my', 'no'])
print(output)

此代码输出

True
True
False

如何将此值作为元组返回

>>> output
(True,  True,  False)

任何想法都表示赞赏。

4 个答案:

答案 0 :(得分:1)

如果要修改任何将事物打印到返回事物的代码中的代码,则必须:

  1. 在顶部创建一个空集合。
  2. 使用将值添加到集合中的调用替换每个print调用。
  3. 退回收藏。
  4. 所以:

    def my_check(str1, list1):
        result = () # create an empty collection
        words = str1.split()
        x = 1
        for l in range(len(list1)):
            for i in range(len(words)):
                if list1[l] == words[i]:
                    x = x+1
            if (x > 1):
                result += (True,) # add the value instead of printing
                x = 1
            else:
                result += (False,) # add the value instead of printing
        return result # return the collection
    

    这对元组来说有点尴尬,但它确实有效。你可能会考虑使用一个列表,因为这不那么笨拙(如果你真的需要转换它,最后总是return tuple(result)。)

答案 1 :(得分:0)

拯救的发电机(编辑:第一次倒退)

def my_check(str1, list1):
    return tuple(w in str1.split() for w in list1)

答案 2 :(得分:0)

考虑到效率,我们首先应该从str1.split()构建一个集合,因为集合中的查询项比列表中的查询项快得多,如下所示:

def my_check(str1, list1):
    #build a set from the list str1.split() first
    wordsSet=set(str1.split())
    #build a tuple from the boolean generator
    return tuple((word in wordsSet) for word in list1)

答案 3 :(得分:0)

您可以直接在字符串中检查字符串,因此不需要split()。所以这也有效:

def my_check(str1, list1):
    return tuple(w in mystr for w in mylist)
    # return [w in mystr for w in mylist] # Much faster than creating tuples

但是,由于通常不需要返回元组而不是新列表,因此您应该只能使用上面的直接列表解析(如果有的话,您可以始终将列表转换为代码下游的元组至)。

python结果:

In [117]: %timeit my_check_wtuple('my name is ide3',  ['is',  'my', 'no'])  
100000 loops, best of 3: 2.31 µs per loop

In [119]: %timeit my_check_wlist('my name is ide3',  ['is',  'my', 'no'])  
1000000 loops, best of 3: 614 ns per loop