让我们假设以下列表
my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']
我想编写一个以两个参数作为输入的函数 其中 m 是我想要查找的字符串字符(例如“ff”),n 是我想要输出的整数字符串数量。
所以def contains_strings('ff', 2):
应该输出:
['coffee', 'insufficient']
两个单词都包含“ff”,总共输出2个。第二个参数可以是随机的。所以我不在乎函数是否输出。 ['咖啡', '不足'] 或 ['差异', '不足']
我只能编写一个能够输出以某些字符开头的单词的函数:
import random as _random
my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']
def starting_letters(m: str, n: int):
a = list(filter(lambda x: x.lower().startswith(m), my_list))
print(_random.choices(a, k=n))
starting_letters('c', 2)
输出:
['coffee', 'cat']
最佳答案
也许像这样:
import random as _random
my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']
def contains_strings(m: str, n: int):
a = list(filter(lambda x: m in x.lower(), my_list))
return _random.sample(a, k=n)
print(contains_strings('ff', 2))
#['coffee', 'insufficient']
关于python - 只打印列表中包含某些字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69595586/