📜  Python - 提取具有偶数长度字符串的行

📅  最后修改于: 2022-05-13 01:55:05.446000             🧑  作者: Mango

Python - 提取具有偶数长度字符串的行

在本文中,我们有一个给定的矩阵,提取偶数长度的行。

方法 #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))


输出

方法 #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))
输出