【问题标题】:Python Convert String of String and Bool To ListPython将String和Bool的字符串转换为List
【发布时间】:2019-10-21 09:16:48
【问题描述】:

我有一个字符串:

my_string = "'T1', 'T2', 'T3', 'T4', True, False"

我想转换成这样的列表

my_list = ['T1', 'T2', 'T3', True, False]

我尝试过my_string.split(', '),但它会将TrueFalse 转换为str,这是我不想要的。

我可以写一个函数,但我觉得有一些 Python 的东西,而且很容易做到这一点。

最好的方法是什么?

【问题讨论】:

    标签: python string list boolean


    【解决方案1】:

    您可以使用ast.literal_evalturn a string representation of a list into a list。要使您的字符串成为列表的表示形式,您需要添加左括号和右括号。

    from ast import literal_eval
    my_string = "'T1', 'T2', 'T3', 'T4', True, False"
    my_list = literal_eval("[" + my_string + "]")
    print(my_list)
    #['T1', 'T2', 'T3', 'T4', True, False]
    

    可以看到最后两个元素的类型是bool

    print([type(x) for x in my_list])
    #[str, str, str, str, bool, bool]
    

    更新

    @Chris_Rands 提出的更简洁的解决方案

    my_list = list(literal_eval(my_string))
    

    【讨论】:

    • list(literal_eval(my_string)) 可能更整洁
    • 您的解决方案在我提供的示例中完美运行,但在我的情况下,有时我的主字符串中只有一个字符串“'T1'”,在这种情况下列表(literal_eval(my_string) ) 不能满足我的需要。
    【解决方案2】:

    一种快速的方法是使用列表理解:

    [
      value.strip() if value.strip().startswith("'") else value == 'True' 
      for value in string.split(',')
    ]
    

    pault 答案看起来更好:)

    【讨论】:

    • 也谢谢你,比你提到的 Pault 的回答要长一点,并且为我的需要工作,所以我会坚持他的:)
    【解决方案3】:

    所以你真的很接近并且实际上有一半的解决方案,你现在需要做的就是遍历列表并将字符串“True”转换为布尔 True。以下是完整的解决方案:

    string = "'T1', 'T2', 'T3', 'T4', True, False"
    list = string.split(', ') #Split string into list
    
    number = 0   #create a number so you can track what element of the list you are at
    
    for i in list: #For each item in the list
        if i.upper() == 'TRUE':
            list[number] = True #Replace any 'True' with bool True
            number += 1 #Move number to next item in list
        elif i.upper() == 'FALSE':
            list[number] = False
            number += 1
        else:
            number += 1 #If item is not 'True' or 'False' go to to next item
    print(list)
    

    有更紧凑和更优雅的方法可以做到这一点,但我保持简单,以便于理解。 i 之后的 .upper 表示您输入 True 或 TRue 或 TrUe 或 TRUE 等的任何方式都将转换为其他两种解决方案不会的 bool True。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 2019-11-30
      相关资源
      最近更新 更多