📜  Python - 测试所需的字符串长度

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

Python - 测试所需的字符串长度

给定一个字符串列表,检查所有字符串是否与第二个大小列表中的所需字符串长度匹配。

方法#1:使用循环

在这种情况下,我们对所有字符串,则将结果标记为 false。

Python3
# Python3 code to demonstrate working of 
# Test for desired String Lengths
# Using loop
  
# initializing string list
test_list = ["Gfg", 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Lengths list 
len_list = [3, 2, 4, 3, 5]
  
res = True
for idx in range(len(test_list)):
      
    # checking for string lengths
    if len(test_list[idx]) != len_list[idx]:
        res = False
        break
  
# printing result 
print("Are all strings of required lengths : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test for desired String Lengths
# Using all()
  
# initializing string list
test_list = ["Gfg", 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Lengths list
len_list = [3, 2, 4, 3, 5]
  
# all() used to check for each element for length
res = all(len(test_list[idx]) == len_list[idx]
          for idx in range(len(test_list)))
  
# printing result
print("Are all strings of required lengths : " + str(res))


输出
The original list is : ['Gfg', 'is', 'best', 'for', 'geeks']
Are all strings of required lengths : True

方法 #2:使用 all()

如果所有长度匹配等于来自其他列表的所需长度,则返回 True。

蟒蛇3

# Python3 code to demonstrate working of
# Test for desired String Lengths
# Using all()
  
# initializing string list
test_list = ["Gfg", 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Lengths list
len_list = [3, 2, 4, 3, 5]
  
# all() used to check for each element for length
res = all(len(test_list[idx]) == len_list[idx]
          for idx in range(len(test_list)))
  
# printing result
print("Are all strings of required lengths : " + str(res))
输出
The original list is : ['Gfg', 'is', 'best', 'for', 'geeks']
Are all strings of required lengths : True