关于replace:Python:将字符串列表转换为布尔值,其中布尔值以字符串形式出现

Python: convert list of strings to booleans where boolean is present in string form

本问题已经有最佳答案,请猛点这里访问。

如何用布尔型True1替换"True"

1
mylist = ["Saturday","True"]

我尝试过替换,但得到了错误:

1
TypeError: replace() argument 2 must be str, not bool

事先谢谢!


使用列表的理解:

1
result = [ True if x =="True" else x for x in mylist  ]

由于手术的编辑评论

你可以使用一个字典的一些值的变换:

1
2
3
4
5
6
7
8
9
10
>>> changes = {"True": True,
...            "False": False,
...            "Lemon":"Gin Lemon"
...           }
>>>
>>> mylist = ["Saturday","True","False","Lemon","Others" ]
>>>
>>> [ changes.get( x, x ) for x in mylist ]

['Saturday', True, False, 'Gin Lemon', 'Others']

在TIP是使用Python字典,一个默认值:get

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.