📜  Python – 将字符串真值转换为布尔值

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

Python – 将字符串真值转换为布尔值

给定一个字符串列表,将字符串真值转换为布尔值。

方法#1:使用列表推导

在此,我们只检查 True 值,其余值自动转换为 False 布尔值。

Python3
# Python3 code to demonstrate working of 
# Convert String Truth values to Boolean
# Using list comprehension
  
# initializing lists
test_list = ["True", "False", "True", "True", "False"]
  
# printing string
print("The original list : " + str(test_list))
  
# using list comprehension to check "True" string
res = [ele == "True" for ele in test_list]
  
# printing results 
print("The converted Boolean values : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert String Truth values to Boolean
# Using map() + lambda
  
# initializing lists
test_list = ["True", "False", "True", "True", "False"]
  
# printing string
print("The original list : " + str(test_list))
  
# using map() to extend and lambda to check "True" string
res = list(map(lambda ele: ele == "True", test_list))
  
# printing results 
print("The converted Boolean values : " + str(res))


输出
The original list : ['True', 'False', 'True', 'True', 'False']
The converted Boolean values : [True, False, True, True, False]

方法 #2:使用 map() + lambda

在此,我们采用相同的方法,只是解决问题的方法不同。 map() 用于扩展由 lambda函数计算的值的逻辑。

Python3

# Python3 code to demonstrate working of 
# Convert String Truth values to Boolean
# Using map() + lambda
  
# initializing lists
test_list = ["True", "False", "True", "True", "False"]
  
# printing string
print("The original list : " + str(test_list))
  
# using map() to extend and lambda to check "True" string
res = list(map(lambda ele: ele == "True", test_list))
  
# printing results 
print("The converted Boolean values : " + str(res))
输出
The original list : ['True', 'False', 'True', 'True', 'False']
The converted Boolean values : [True, False, True, True, False]