python - 只打印列表中包含某些字符的字符串

标签 python python-3.x

让我们假设以下列表

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/

相关文章:

python - 为什么内置函数 `any(b'\x0 0')` 在 python2 和 python3 之间表现不同?

python - 派斯帕克 2 : KMeans The input data is not directly cached

python - 如何将转换应用于 pandas 数据框列表?

python - (如何)我可以在 jupyter (ipython) 中并排运行 python 2.7 和 3.4 笔记本吗?

python - Python 3.10 中的 Tkinter?

python - Flask 重定向后的 Twilio MessagingResponse()

python - Beautiful Soup Unicode 编码错误

python - 二元交叉熵与 2 个类别的分类交叉熵

python - 两个连续的 yield 语句如何在 python 中工作?

python-3.x - 如何调整 st.image 显示的图像大小