簡體   English   中英

只從包含某些字符的列表中打印出字符串

[英]Only print out strings from a list that contain certain characters

讓我們假設以下列表

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']

這是我將如何做到的:

import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']

def starting_letters(m: str, n: int):
    a = list(filter(lambda x: m in x.lower(), my_list)) 
    print(_random.sample(a, n))

注意我是如何用random.choices()方法替換random.sample()方法的。 原因是因為使用random.choices()方法,您可能會在輸出中多次從同一索引中獲取元素,而random.sample()方法確保每個返回的元素都來自列表的唯一索引。

您可以在此處使用regex來匹配字符串中的模式

import re
import random as _random

my_list = ['bottle', 'coffee', 'insufficient', 'differential', 'cat']


def contains_pattern(pattern: str, n: int):
    regex = re.compile(f'{pattern}')
    a = [ans for ans in my_list if regex.search(ans)]
    return _random.choices(a, k=n)

print(contains_pattern("ff",2))

# ['insufficient', 'coffee']

將隨機導入為 _random

my_list = ['瓶子','咖啡','不足','差異','貓']

def starting_letters(m: str, n: int): a = list(filter(lambda x: m in x, my_list)) print(_random.choices(a, k=n))

起始字母('ff',2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM