Python - 提取具有偶数长度字符串的行
在本文中,我们有一个给定的矩阵,提取偶数长度的行。
Input : test_list = [[“gfg”, “is”, “best”], [“best”, “good”, “geek”], [“is”, “better”], [“for”, “cs”]]
Output : [[‘best’, ‘good’, ‘geek’], [‘is’, ‘better’]]
Explanation : All strings are of even length.
Input : test_list = [[“gfg”, “is”, “best”], [“best”, “good”, “geeks”], [“is”, “better”], [“for”, “cs”]]
Output : [[‘is’, ‘better’]]
Explanation : All strings are of even length.
方法 #1:使用 all() + 列表推导 + len()
在此,我们检查每行中的所有字符串及其长度,并检查长度是否为偶数,如果行中所有字符串的长度为偶数,则将其添加到结果列表中。
Python3
# Python3 code to demonstrate working of
# Extract rows with Even length strings
# Using all() + list comprehension + len()
# initializing list
test_list = [["gfg", "is", "best"], ["best", "good", "geek"], ["is", "better"], ["for", "cs"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for all elements in row
res = [row for row in test_list if all(len(ele) % 2 == 0 for ele in row)]
# printing result
print("Rows with even length : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract rows with Even length strings
# Using filter() + lambda + len()
# initializing list
test_list = [["gfg", "is", "best"], ["best", "good", "geek"], ["is", "better"], ["for", "cs"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for all elements in row
# filtering done using filter() and lambda
res = list(filter(lambda row : all(len(ele) % 2 == 0 for ele in row), test_list))
# printing result
print("Rows with even length : " + str(res))
The original list is : [[‘gfg’, ‘is’, ‘best’], [‘best’, ‘good’, ‘geek’], [‘is’, ‘better’], [‘for’, ‘cs’]]
Rows with even length : [[‘best’, ‘good’, ‘geek’], [‘is’, ‘better’]]
方法 #2:使用 filter() + lambda + len()
在此,我们使用 filter() + lambda、len() 执行过滤任务,如上述方法,执行获取每个字符串长度的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Extract rows with Even length strings
# Using filter() + lambda + len()
# initializing list
test_list = [["gfg", "is", "best"], ["best", "good", "geek"], ["is", "better"], ["for", "cs"]]
# printing original list
print("The original list is : " + str(test_list))
# checking for all elements in row
# filtering done using filter() and lambda
res = list(filter(lambda row : all(len(ele) % 2 == 0 for ele in row), test_list))
# printing result
print("Rows with even length : " + str(res))
The original list is : [[‘gfg’, ‘is’, ‘best’], [‘best’, ‘good’, ‘geek’], [‘is’, ‘better’], [‘for’, ‘cs’]]
Rows with even length : [[‘best’, ‘good’, ‘geek’], [‘is’, ‘better’]]