如何将字符串列表转换为正确的列表?
How to convert a string list to a proper list?
我正在尝试解决这个问题:
Write a program that takes two lists and returns a list that contains all the elements of the first list minus all the common elements between the two lists.
编码部分非常简单。这是:
list1=input()
list2=input()
for i in list1:
if i in list2:
list1.remove(i)
else:
pass
print(list1)
我在这里面临的问题是 list1
和 list2
是字符串。
取list1=‘[1,2,3,4]’
。
我需要将 list1
转换为 [1,2,3,4]
。
我尝试了 split()
和 join()
中建议的方法 How to convert list to string
但我失败了。
如何将 '[1,2,3,4]'
转换为 [1,2,3,4]
?
你有两个选择,你可以加载为json
:
import json
json.loads('[1,2,3,4]')
# [1, 2, 3, 4]
或者您可以使用 ast.literal_eval
评估字符串
from ast import literal_eval
literal_eval('[1,2,3,4]')
# [1, 2, 3, 4]
使用 ast
模块评估字符串,这是安全的:
import ast
ast.literal_eval('[1, 2, 3, 4]')
=> [1, 2, 3, 4]
我会在输入时立即转换它们
在这种情况下你甚至不需要使用逗号
list1=list(input())
list2=list(input())
我正在尝试解决这个问题:
Write a program that takes two lists and returns a list that contains all the elements of the first list minus all the common elements between the two lists.
编码部分非常简单。这是:
list1=input()
list2=input()
for i in list1:
if i in list2:
list1.remove(i)
else:
pass
print(list1)
我在这里面临的问题是 list1
和 list2
是字符串。
取list1=‘[1,2,3,4]’
。
我需要将 list1
转换为 [1,2,3,4]
。
我尝试了 split()
和 join()
中建议的方法 How to convert list to string
但我失败了。
如何将 '[1,2,3,4]'
转换为 [1,2,3,4]
?
你有两个选择,你可以加载为json
:
import json
json.loads('[1,2,3,4]')
# [1, 2, 3, 4]
或者您可以使用 ast.literal_eval
from ast import literal_eval
literal_eval('[1,2,3,4]')
# [1, 2, 3, 4]
使用 ast
模块评估字符串,这是安全的:
import ast
ast.literal_eval('[1, 2, 3, 4]')
=> [1, 2, 3, 4]
我会在输入时立即转换它们 在这种情况下你甚至不需要使用逗号
list1=list(input())
list2=list(input())