繁体   English   中英

列表以元组返回python

[英]list to tuple return in python

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

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)

任何想法表示赞赏。

如果要修改将代码打印为返回内容的代码的任何代码,则必须执行以下操作:

  1. 在顶部创建一个空集合。
  2. 用将值添加到集合的调用替换每个print调用。
  3. 返回集合。

所以:

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) )。

救援人员(编辑:第一次倒退)

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

考虑到效率,也许我们应该首先从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)

您可以直接在字符串中检查字符串,因此不需要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

暂无
暂无

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

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