繁体   English   中英

我如何获得给定两个单词的所有组合列表?

[英]how do i get a list of all combinations for both words given?

我试图想出一种方法来以所有可能的(但常见的)方式(如小写和大写和大写)获取像“是”这样的单词列表。 然后我发现你不能在这个 function 中放两个词(“sup”和“hello”)。 有没有办法可以用这个 function 将所有单词放在一个列表中,还是应该重新开始?

def case_insensetive(text) :
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    print (insensetive_string)

try :
   case_insensetive("sup","hello")
except :
   raise Exception ("you screwed something")

这是map() function 的典型工作。

此外,在 function 中使用return而不是print

def case_insensetive(text):
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    return insensetive_string


words = ['yes', 'hello']

r = list(map(case_insensetive, words))

print(r)

Output:

[['yes', 'YES', 'Yes'], ['hello', 'HELLO', 'Hello']]

如果您想要一个列表,而不是嵌套列表:

flat_list = [item for sublist in r for item in sublist]
print(flat_list)

['yes', 'YES', 'Yes', 'hello', 'HELLO', 'Hello']

只需传递一个任意参数(*args)..然后可以任意数量的 arguments..

def case_insensetive(*texts):
    insensetive_string = []
    for text in texts:
        insensetive_string+=[text.lower(),text.upper(),text.capitalize()]
    print(insensetive_string)

case_insensetive("sup",'hello')

Output:['sup','SUP','Sup','你好','你好','你好']

暂无
暂无

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

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