Python程序:从另一个列表中提取至少指定长度的字符串


当需要从另一个列表中提取至少具有指定字符数的字符串时,可以使用列表推导式。

示例

以下是演示。

Open Compiler
my_list = ["Python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) my_char_list = ['e', 't', 's', 'm', 'n'] my_key = 2 print("The value of key is ") print(my_key) my_result = [element for element in my_list if sum(ch in my_char_list for ch in element) >= my_key] print("The resultant list is :") print(my_result)

输出

The list is :
['Python', 'is', 'fun', 'to', 'learn']
The value of key is
2
The resultant list is :
['Python', 'learn']

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 定义一个字符串列表并在控制台中显示。

  • 定义另一个字符列表。

  • 定义一个键值并在控制台中显示。

  • 使用列表推导式迭代列表元素,并获取字符列表中字符的总和。

  • 将其与键值进行比较。

  • 如果大于或等于键值,则将其存储到列表中并赋值给变量。

  • 这将在控制台中显示为输出。

更新于:2021年9月16日

浏览量:100

开启你的职业生涯

完成课程获得认证

开始学习
广告